Well, simple. Use hashset.
Time - . Space - .
public class Solution {
public bool ContainsDuplicate(int[] nums) {
var seen = new HashSet<int>();
foreach (int n in nums)
{
if (seen.Contains(n))
return true;
seen.Add(n);
}
return false;
}
}Other approaches?
Sorting + Adjacent Check,
Basically, sort the array. If duplicates exist, they will be adjacent.
Time - . Space - (if in-place sort).
public class Solution
{
public bool ContainsDuplicate(int[] nums)
{
Array.Sort(nums);
for (int i = 1; i < nums.Length; i++)
{
if (nums[i] == nums[i - 1])
return true;
}
return false;
}
}Another hashset pattern,
HashSet One-Liner Trick (Size Comparison)
public class Solution
{
public bool ContainsDuplicate(int[] nums)
{
return nums.Length != new HashSet<int>(nums).Count;
}
}This works because a HashSet only keeps unique elements, so size reduces if duplicates exist.