EasyLeetCode #217Arrays & Hashing
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.
Constraints
1 <= nums.length <= 10^5, -10^9 <= nums[i] <= 10^9
Examples
Input: nums = [1,2,3,1]
Output: true
Input: nums = [1,2,3,4]
Output: false
Solution
Approach
Use a HashSet to track seen numbers. If a number is already in the set, return true. Otherwise, add it and continue.
def containsDuplicate(nums):
return len(nums) != len(set(nums))Complexity
Time:O(n)
Space:O(n)
Hints
- 1.What data structure provides O(1) lookup and insertion?
- 2.Consider using a Set
Asked at
Google