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 absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
给出一个数组,让判断是否存在nums[i] == nums[j] 而且下标i和j的差<=k
思路:
既然要求相等的俩数下标的差不能超过k,
那么当然是下标的差越小越好,
当遍历到相同的数字时,如果同时有好几个相同的数字,那自然是取之前遍历过的最右边的数字的下标,
比如example2中的[1,0, 1, 1],遍历到最后一个1的时候,它前面有2个相同的数字1,要选最右边的1,这样下标差才最小。
既然这样,只需要一个hash map, 保存数字和它对应的最新的下标(最右边的),
遇到相同的数字时,用当前下标减去hash map中保存的下标,只要差<=k,就返回true.
其实不需要计算差的绝对值,因为是从左到右遍历的,右边的下标肯定比左边的大。
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<>();
int i = 0;
for(int num : nums) {
if(map.containsKey(num)) {
if(i - map.get(num) <= k) return true;
}
map.put(num, i);
i++;
}
return false;
}