Description:
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

题意:给定一个一维数组num和一个最大距离k;要求判断数组中是否存在两个不同位置相等的元素,且这两个元素之间的最大距离为k;

解法一:最简单的办法就是遍历所有的可能,我们对每一个元素,判断在最大距离k之内是否存在相等的元素;

Java
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j <= Math.min(i + k, nums.length - 1); j++) {
if (nums[i] == nums[j]) {
return true;
}
}
}
return false;
}
}

解法二:我们可以利用哈希表来实现,以元素值及下标作为键值对;在遍历数组的时候,将哈希表中不存在的元素存入到表中,当遇到表中存在的元素时,比较两者的下标差是否在最大距离k之内,如果没有,则更新此元素的下标为当前元素下标,继续遍历直到找到相等元素亦或者遍历完数组;

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