File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments