Last active
August 29, 2015 14:22
-
-
Save fever324/1292618fbb7cabe624eb to your computer and use it in GitHub Desktop.
Contains Duplicate II
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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