Check for Duplicate Values in Array containing random number which are repeating or distinct. Our job is to tell if the array contains repeating elements.
Example: 3, 4, 8, 6, 7, 9, 4, 77 Ans = True. 4 appears twice
Example: 3, 8, 6, 7, 9, 4, 77 Ans = False. No dups
Solution:
We loop through the array one element at a time and we throw it in to a hashset if we didn't do this before. But if we already visit this number before, then we can check it in the set and quickly tell the list has distinct elements or not.
public bool ContainsDuplicate(int[] nums) {
HashSet<int> hs = new HashSet<int>();
for(int i=0;i < nums.Length; i++) {
if(!hs.Contains(nums[i]))
hs.Add(nums[i]);
else
return true;
}
return false;
}