# Time limit exceed in Java

• Why all my three solution get a time limit exceed. Is there any problem with the judge system?

//solution 1 : time limit exceed
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(nums == null || nums.length <= 1) return false;

for(int i = 1; i < nums.length; i ++){
int low = Math.max(0, i - k); int high = Math.min(nums.length - 1, i + k);
for(int j = low; j <= high; j ++){
if(nums[j] == nums[i] && j != i)
return true;
}
}
return false;
}

//solution 2 : use a hashmap, time limit exceed..
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(nums == null || nums.length <= 1) return false;

HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i ++){
if(table.containsKey(nums[i]) && table.get(nums[i]) - i <= k)
return true;
else
table.put(nums[i], i);
}
return false;
}

//solution3 : use a slide window and a set. time limit exceed.
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(nums == null || nums.length <= 1) return false;

Set<Integer> windowNum  = new HashSet<Integer>();
int start = 0; int end = 0;

for(int i = 0; i < nums.length; i ++){
if(! windowNum.contains(nums[i])){
end ++;
}
else
return true;

if(end - start > k){
windowNum.remove(nums[start]);
start ++;
}
}
return false;
}

• Solution 2

if(table.containsKey(nums[i]) && table.get(nums[i]) - i <= k)

shoud be

if(table.containsKey(nums[i]) && i - table.get(nums[i]) <= k)

• yes, thank you! you are right.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.