My solution for the leet code problem to search an array of ints for duplicate values and return a boolean seems quite efficient (< 90% of submissions runtime). However, I am currently reviewing Data Structures and Algorithms and I wonder if there is a more efficient approach to this, since if my counting is correct my solution will run at O(n) for worst case scenarios. I am still new to C# (I mostly code in js).
public bool ContainsDuplicate(int[] nums) {
HashSet<int> singles = new HashSet<int>();
for(int i = 0; i < nums.Length;i++)
{
if (singles.Contains(nums[i]))
return true;
singles.Add(nums[i]);
}
return false;
}
1 Answer 1
This can be slightly optimized by not using Contains()
but checking the returned value from Add()
. If the item is allready contained in the HashSet<T>
calling Add()
will return false
.
public bool ContainsDuplicate(int[] nums) {
HashSet<int> singles = new HashSet<int>();
for(int i = 0; i < nums.Length;i++)
{
if (!singles.Add(nums[i]))
{
return true;
}
}
return false;
}
-
1\$\begingroup\$ How about a one liner:
return new HashSet<int>(nums).Count < nums.Length
? \$\endgroup\$Jesse C. Slicer– Jesse C. Slicer2021年11月12日 20:46:43 +00:00Commented Nov 12, 2021 at 20:46 -
1\$\begingroup\$ This would add all items first where in my answer it would return at the first duplicate. \$\endgroup\$Heslacher– Heslacher2021年11月13日 08:19:22 +00:00Commented Nov 13, 2021 at 8:19
-
\$\begingroup\$ @Heslacher yes. \$\endgroup\$Jesse C. Slicer– Jesse C. Slicer2021年11月13日 20:37:17 +00:00Commented Nov 13, 2021 at 20:37
O(n)
? because theContains
has an iterator as well which puts itO(n^2)
\$\endgroup\$