我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/contains-duplicate-ii/description/

题目描述:

LeetCode219——存在重复元素II

知识点:哈希表、滑动窗口法

思路:滑动窗口法

本题是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解题报告:

LeetCode219——存在重复元素II

 

相关文章:

  • 2021-07-05
  • 2021-11-04
  • 2021-06-18
  • 2021-09-12
  • 2022-02-22
  • 2021-05-10
  • 2021-10-05
猜你喜欢
  • 2022-12-23
  • 2021-11-02
  • 2021-07-26
  • 2021-09-21
  • 2021-09-05
  • 2022-01-02
  • 2021-10-21
相关资源
相似解决方案