-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContainsDuplicateII.java
More file actions
42 lines (37 loc) · 1.03 KB
/
ContainsDuplicateII.java
File metadata and controls
42 lines (37 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*Given an array of integers and an integer k, find out whether there are two distinct indices
i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.*/
import java.util.HashMap;
public class ContainsDuplicatesII {
public static boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer,Integer> h=new HashMap<Integer,Integer>();
int flag=0;
for(int i=0;i<nums.length;i++)
{
if(!h.containsKey(nums[i]))
h.put(nums[i], i);
else
{
int j=h.get(nums[i]);
if(i-j<=k)
{
flag=1;
break;
}
else
h.put(nums[i], i);
}
}
if(flag==1)
return true;
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] x = { 1,0,1,1 };
boolean check=containsNearbyDuplicate(x,1);
if(check==true)
System.out.println("yes, it contains duplicate at a distance of k");
else
System.out.println("nope it does not contain");
}
}