Given an integer array
nums
, returntrue
if any value appears at least twice in the array, and returnfalse
if every element is distinct.
Set
This problem is trivialized by the use of a data structure with constant () lookup time. We can use C#‘s HashSet data structure.
public bool ContainsDuplicate(int[] nums)
{
HashSet<int> seenNums = new HashSet<int>();
for(int i = 0; i < nums.Length; i++){
if(!seenNums.Add(nums[i])){
return true;
}
}
return false;
}
The time complexity for our solution is , since in the worst case (i.e. no duplicates), we must look at every element in the nums
array. The space complexity is also , since we are copying every element to a new data structure.