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 jis at most k.
题意:给出一个数组nums和数k,问数组中是否存在两个数相等,并且下标之差小于k
思路:用HashMap,在遍历数组过程中,更新hashmap中nums[i]所对应的下标,如果hash中存在nums[i],看i与nums[i]的hash值是否小于k,如果小于k,说明满足条件, 否则将nums[i]的hash更新为i
代码如下:
class Solution
{
public boolean containsNearbyDuplicate(int[] nums, int k)
{
//Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++)
{
if (hm.containsKey(nums[i]))
{
if (i - hm.get(nums[i]) <= k) return true;
}
hm.put(nums[i], i);
}
return false;
}
}