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.
题目标签:Array, Hash Table
题目给了我们一个nums array 和一个 k, 让我们找到两个 相同的项,并且它们的index 差值 小于等于 k。
这次我们依然要利用Hash Table,因为这次需要比较它们的index, 所以需要key 和value, 不同于 包含重复项之一 那一题,只需要比较数字。
遍历nums array, 如果nums[i] 不在hash table 里的话,就把 nums[i] 当作key, i 当作 value 存入hash table;
如果hash table 有nums[i]的话,就比较两个index 的差值,如果小于等于 k, 就返回true。
Java Solution:
Runtime beats 52.19%
完成日期:05/27/2017
关键词:Array, Hash Table
关键点:利用Hash Table, 把nums[i] 当作key, i 当作value 存入Hash Table
public class Solution
{
public boolean containsNearbyDuplicate(int[] nums, int k)
{
if(nums.length == 0 || nums == null)
return false; HashMap<Integer, Integer> unique = new HashMap<>(); for(int i=0; i<nums.length; i++)
{
if(unique.containsKey(nums[i]) && i - unique.get(nums[i]) <= k)
{
return true;
}
else
unique.put(nums[i], i);
} return false;
}
}
参考资料:N/A
LeetCode 算法题目列表 - LeetCode Algorithms Questions List