Skip to content

Instantly share code, notes, and snippets.

@fever324
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fever324/1292618fbb7cabe624eb to your computer and use it in GitHub Desktop.
Save fever324/1292618fbb7cabe624eb to your computer and use it in GitHub Desktop.
Contains Duplicate II
/*
Given an array of integers and an integer k, return true if and only if 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.
*/
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
int value = map.get(nums[i]);
if ((i - value) <= k) {
return true;
} else {
map.put(nums[i], i);
}
} else {
map.put(nums[i],i);
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment