LeetCode刷题实战219:存在重复元素 II
共 2714字,需浏览 6分钟
·
2021-03-24 14:00
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;
}
}