Algorithm


Problem Name: 217. Contains Duplicate

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

 

Example 1:

Input: nums = [1,2,3,1]
Output: true

Example 2:

Input: nums = [1,2,3,4]
Output: false

Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true

 

Constraints:

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 10
 

Code Examples

#1 Code Example with C Programming

Code - C Programming


int cmp(const void *a, const void *b) {
    return *(int *)a - *(int *)b;
}
bool containsDuplicate(int* nums, int numsSize) {
    int i;
    
    qsort(nums, numsSize, sizeof(int), cmp);
    
    for (i = 1; i  <  numsSize; i ++) {
        if (nums[i] == nums[i - 1]) return true;
    }
    
    return false;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [1,2,3,1]

Output

x
+
cmd
true

#2 Code Example with Java Programming

Code - Java Programming


class Solution {
  public boolean containsDuplicate(int[] nums) {
    return Arrays.stream(nums).boxed().collect(Collectors.toSet()).size() < nums.length;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [1,2,3,1]

Output

x
+
cmd
true

#3 Code Example with Javascript Programming

Code - Javascript Programming


const containsDuplicate = function(nums) {
  const hash = {};
  for (let el of nums) {
    if (hash.hasOwnProperty(el)) {
      return true;
    } else {
      hash[el] = 1;
    }
  }
  return false;
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [1,2,3,4]

Output

x
+
cmd
false

#4 Code Example with Python Programming

Code - Python Programming


class Solution:
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        dic=dict()
        for num in nums:
            if not num in dic:
                dic[num]=1
            else:
                return True
        return False
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [1,2,3,4]

Output

x
+
cmd
false

#5 Code Example with C# Programming

Code - C# Programming


using System.Collections.Generic;

namespace LeetCode
{
    public class _0217_ContainsDuplicate
    {
        public bool ContainsDuplicate(int[] nums)
        {
            var set = new HashSet < int>();
            foreach (var num in nums)
            {
                if (set.Contains(num)) return true;
                set.Add(num);
            }
            return false;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [1,1,1,3,3,4,3,2,4,2]

Output

x
+
cmd
true
Advertisements

Demonstration


Previous
#216 Leetcode Combination Sum III Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#218 Leetcode The Skyline Problem Solution in C, C++, Java, JavaScript, Python, C# Leetcode