LeetCode219——存在重复元素II
我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/contains-duplicate-ii/description/
题目描述:
知识点:哈希表、滑动窗口法
思路:滑动窗口法
本题是LeetCode217——存在重复元素的加强版,由于题目要求i和j的绝对值最大为k,因此我们需要设立一个滑动窗口。
滑动窗口的最大宽度是k,用hashMap来记录滑动窗口中出现的各个元素及其数量。
时间复杂度和空间复杂度均是O(n),其中n为数组的长度。
JAVA代码:
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
int left = 0;
int right = -1; //[left, right]为我们的滑动窗口
HashMap<Integer, Integer> hashMap = new HashMap<>();
while(left < nums.length) {
if(right + 1 < nums.length && right - left < k) {
right++;
if(hashMap.containsKey(nums[right])) {
return true;
}else {
hashMap.put(nums[right], 1);
}
}else {
hashMap.put(nums[left], hashMap.get(nums[left]) - 1);
if(hashMap.get(nums[left]) == 0) {
hashMap.remove(nums[left]);
}
left++;
}
}
return false;
}
}
LeetCode解题报告: