一、問題描述
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.
二、問題分析
如果是最笨的方法,顯然是從頭開始遍歷,挨個與後面的元素作比較;但這樣有嚴重的重複訪問;因此需要一個存儲結構來記錄已經訪問過的元素,並且在重新取某個元素的時候時間儘量少,而且這個存儲結構可以既存元素又存索引,因此可以選用hashMap。邏輯上並不複雜,具體的看代碼,有一點需要注意的就是如果nums[i]=nums[j]並且j-i>k,那麼這時,應該重新put一下元素對應的索引值,因爲是往後訪問,而新的索引值顯然更有潛力。
三、Java AC代碼
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
if (nums==null || nums.length==0) {
return false;
}
int index = 0;
for(int i=0;i<nums.length;i++){
if (map.containsKey(nums[i])) {
index = map.get(nums[i]);
if (i-index<=k) {
return true;
}else {
map.put(nums[i], i);
}
}else {
map.put(nums[i], i);
}
}
return false;
}