Skip to content

Commit 7e36667

Browse files
authored
Create 0219-contains-duplicate-II.cs
1 parent 926a6b0 commit 7e36667

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

csharp/0219-contains-duplicate-II.cs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
3+
Approach:
4+
1. We will use a HashSet to store the elements.
5+
2. We will iterate through the array and add the elements to the HashSet.
6+
3. If the element is already present in the HashSet, we will return true.
7+
4. If the difference between the current index and the previous index is greater than k, we will remove the element at the previous index.
8+
5. If we reach the end of the array, we will return false.
9+
10+
Time Complexity: O(n)
11+
Space Complexity: O(n)
12+
13+
*/
14+
public class Solution {
15+
public bool ContainsNearbyDuplicate(int[] nums, int k) {
16+
HashSet<int> hs = new HashSet<int>();
17+
int i,j;
18+
i = j = 0;
19+
while(j<nums.Length) {
20+
if( Math.Abs(i-j) <= k) {
21+
if(!hs.Contains(nums[j])) {
22+
hs.Add(nums[j]);
23+
j++;
24+
}
25+
else {
26+
return true;
27+
}
28+
}
29+
else {
30+
hs.Remove(nums[i]);
31+
i++;
32+
}
33+
}
34+
return false;
35+
}
36+
}

0 commit comments

Comments
 (0)