?LeetCode刷題實(shí)戰(zhàn)219:存在重復(fù)元素 II
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
示例
示例 1:
輸入: nums = [1,2,3,1], k = 3
輸出: true
示例 2:
輸入: nums = [1,0,1,1], k = 1
輸出: true
示例 3:
輸入: nums = [1,2,3,1,2,3], k = 2
輸出: false
解題
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer,Integer> hm = new HashMap<>();
for(int i=0;i<nums.length;i++){
if(hm.containsKey(nums[i])){
int sub = i - hm.get(nums[i]);
if(sub <= k)
return true;
else
hm.put(nums[i],i);
}
else
hm.put(nums[i],i);
}
return false;
}
}
LeetCode1-200題匯總,希望對你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)201:數(shù)字范圍按位與
LeetCode刷題實(shí)戰(zhàn)202:快樂數(shù)
LeetCode刷題實(shí)戰(zhàn)203:移除鏈表元素
LeetCode刷題實(shí)戰(zhàn)204:計數(shù)質(zhì)數(shù)
LeetCode刷題實(shí)戰(zhàn)205:同構(gòu)字符串
LeetCode刷題實(shí)戰(zhàn)206:反轉(zhuǎn)鏈表
LeetCode刷題實(shí)戰(zhàn)207:課程表
LeetCode刷題實(shí)戰(zhàn)208:實(shí)現(xiàn) Trie (前綴樹)
LeetCode刷題實(shí)戰(zhàn)209:長度最小的子數(shù)組
LeetCode刷題實(shí)戰(zhàn)210:課程表 II
LeetCode刷題實(shí)戰(zhàn)211:添加與搜索單詞
LeetCode刷題實(shí)戰(zhàn)212:單詞搜索 II
LeetCode刷題實(shí)戰(zhàn)213:打家劫舍 II
LeetCode刷題實(shí)戰(zhàn)214:最短回文串
LeetCode刷題實(shí)戰(zhàn)215:數(shù)組中的第K個最大元素
LeetCode刷題實(shí)戰(zhàn)216:組合總和 III
LeetCode刷題實(shí)戰(zhàn)217:存在重復(fù)元素
LeetCode刷題實(shí)戰(zhàn)218:天際線問題
