-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuestion219.java
More file actions
58 lines (52 loc) · 1023 Bytes
/
Copy pathQuestion219.java
File metadata and controls
58 lines (52 loc) · 1023 Bytes
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
Author: Ananthanarayanan R
Section: Algorithms
Question: 219
*/
import java.util.*;
public class Question219
{
public static boolean containsNearbyDuplicate(int[] nums, int k)
{
if (k>=nums.length)
{
HashSet<Integer> set = new HashSet<>();
for(int i:nums)
set.add(i);
if(set.size()<nums.length)
return true;
}
else
{
LinkedHashSet<Integer> set = new LinkedHashSet<>();
int start = nums[0];
for(int i = 0;i<k+1;i++)
{
set.add(nums[i]);
}
if(set.size()<k+1)
return true;
for(int i = k+1;i<nums.length;i++)
{
//remove first element
set.remove(start);
for(int number:set)
{
start = number;
break;
}
set.add(nums[i]);
if(set.size()<k+1)
return true;
}
}
return false;
}
public static void main(String[] args)
{
int[] nums = {1,2,3,1};
int k = 2;
boolean result = containsNearbyDuplicate(nums,k);
System.out.println(result);
}
}