Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit7e36667

Browse files
authored
Create 0219-contains-duplicate-II.cs
1 parent926a6b0 commit7e36667

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+
publicclassSolution{
15+
publicboolContainsNearbyDuplicate(int[]nums,intk){
16+
HashSet<int>hs=newHashSet<int>();
17+
inti,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+
returntrue;
27+
}
28+
}
29+
else{
30+
hs.Remove(nums[i]);
31+
i++;
32+
}
33+
}
34+
returnfalse;
35+
}
36+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp