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;
}
}