LeetCode 题解工作台

存在重复元素 II

给你一个整数数组 nums 和一个整数 k ,判断数组中是否存在两个 不同的索引 i 和 j ,满足 nums[i] == nums[j] 且 abs(i - j) 。如果存在,返回 true ;否则,返回 false 。 示例 1: 输入: nums = [1,2,3,1], k = 3 输出: …

category

3

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们用一个哈希表 存放最近遍历到的数以及对应的下标。 遍历数组 ,对于当前遍历到的元素 ,如果在哈希表中存在,并且下标与当前元素的下标之差不超过 ,则返回 ,否则将当前元素加入哈希表中。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums 和一个整数 k ,判断数组中是否存在两个 不同的索引 i 和 j ,满足 nums[i] == nums[j]abs(i - j) <= k 。如果存在,返回 true ;否则,返回 false

 

示例 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

 

 

提示:

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • 0 <= k <= 105
lightbulb

解题思路

方法一:哈希表

我们用一个哈希表 d\textit{d} 存放最近遍历到的数以及对应的下标。

遍历数组 nums\textit{nums},对于当前遍历到的元素 nums[i]\textit{nums}[i],如果在哈希表中存在,并且下标与当前元素的下标之差不超过 kk,则返回 true\text{true},否则将当前元素加入哈希表中。

遍历结束后,返回 false\text{false}

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组 nums\textit{nums} 的长度。

1
2
3
4
5
6
7
8
9
class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        d = {}
        for i, x in enumerate(nums):
            if x in d and i - d[x] <= k:
                return True
            d[x] = i
        return False
speed

复杂度分析

指标
时间complexity is O(n) for the hash map or set sliding window approach because each element is processed once and hash operations are O(1). Space complexity is O(min(n,k)) as only the most recent k elements are stored in the hash map or set, keeping memory proportional to the sliding window.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Do you understand why a hash map is necessary instead of nested loops?

  • question_mark

    Notice how the sliding window maintains the k-index constraint efficiently.

  • question_mark

    Ask if the solution handles edge cases like k = 0 or all unique elements.

warning

常见陷阱

外企场景
  • error

    Using nested loops blindly leads to TLE on large arrays.

  • error

    Failing to remove elements outside the k-window from the map or set breaks correctness.

  • error

    Confusing the requirement for indices versus values can result in false positives.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Check for duplicates within k distance but allow a value to repeat multiple times; count total pairs.

  • arrow_right_alt

    Find the first duplicate within k indices and return its pair of indices instead of true/false.

  • arrow_right_alt

    Extend the problem to handle multiple k values dynamically for streaming input arrays.

help

常见问题

外企场景

存在重复元素 II题解:数组·哈希·扫描 | LeetCode #219 简单