Contains Duplicate
Examples
Example 1:
Input: nums = [1, 2, 3, 3]
Output: true
Example 2:
Input: nums = [1, 2, 3, 4]
Output: false
Example 1:
Input: nums = [1, 2, 3, 3]
Output: true
Example 2:
Input: nums = [1, 2, 3, 4]
Output: false
Given an integer array nums, return true if any value appears more than once in the array, otherwise return false.
Use a hash set to record numbers seen so far. Scan the array; if a number is already in the set, we can immediately return true. Otherwise add it and continue. This works for negatives and the single-element edge case because every value is treated the same way.
The set is exactly the collection of elements that have appeared earlier in the scan. The first time any value appears twice, the second occurrence is detected by a membership check, so returning true is correct. If no membership check ever succeeds, all values are unique, so returning false is correct.
O(n)O(n)class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
seen = set()
for num in nums:
if num in seen:
return True
seen.add(num)
return False