1. 题目描述
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 difference between i and j is at most k.
给定一个数组和一个整型k,判断数组中是否有两个相等的值的距离小于k。
2. 解题思路
使用一个HashMap保存这个数组中出现过的元素和该元素的位置,如果出现了重复的元素,判断当前位置和之前保存的位置距离是否在k之内,如果在k之内直接返回true。如果不在k之内,更新k的位置,继续进行判断。如果全部扫描完毕都没有出现满足要求的结果,返回false。
3. Code
import java.util.HashMap;
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
// 不要小看这条语句,提升速度的关键!beats 13%->48%
if(k <= 0) return false;
// <num, pos>
HashMap<Integer, Integer> numMap = new HashMap<>();
for(int i = 0; i < nums.length; ++i)
{
if(numMap.containsKey(nums[i]))
{
if(i - numMap.get(nums[i]) <= k) return true;
}
numMap.put(nums[i], i);
}
return false;
}
}