0219. Contains Duplicate I I

219. 存在重复元素 II #

Difficulty: 简单

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j] ,并且 ij 的差的 绝对值 至多为 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) {
        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;
    }
}

复杂度分析 #

  • 时间复杂度:O(n)。

  • 空间复杂度:O(n)。

题解二:哈希表结构 #

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; ++i) {
            if (set.contains(nums[i])) {
                return true;
            }
            set.add(nums[i]);
            if (set.size() > k) {
                set.remove(nums[i - k]);
            }
        }
        return false;
    }
}

复杂度分析 #

  • 时间复杂度:O(n)。

  • 空间复杂度:O(min(n, k))。

Calendar Dec 4, 2020
Edit Edit this page
本站总访问量:  次 您是本站第  位访问者