美文网首页
[刷题防痴呆] 0219 - 存在重复元素II (Contain

[刷题防痴呆] 0219 - 存在重复元素II (Contain

作者: 西出玉门东望长安 | 来源:发表于2021-12-22 01:35 被阅读0次

题目地址

https://leetcode.com/problems/contains-duplicate-ii/description/

题目描述

219. Contains Duplicate II

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 absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

思路

  • HashSet for 循环.
  • 方法2, hashmap.

关键点

  • 在Contains Duplicate的基础上, 维持一个大小为k的window.
  • 如果i > k, 则将set里的nums[i - k - 1]元素remove掉.

代码

  • 语言支持:Java
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (i > k) {
                set.remove(nums[i - k - 1]);
            }
            if (set.contains(nums[i])) {
                return true;
            }
            set.add(nums[i]);
        }
        
        return false;
    }
}

// hashmap 存index
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                if (i - map.get(nums[i]) <= k) {
                    return true;
                }
            }
            map.put(nums[i], i);
        }
        return false;
    }
}

相关文章

网友评论

      本文标题:[刷题防痴呆] 0219 - 存在重复元素II (Contain

      本文链接:https://www.haomeiwen.com/subject/ozsufrtx.html