LeetCode 题解工作台

必须拿起的最小连续卡牌数

给你一个整数数组 cards ,其中 cards[i] 表示第 i 张卡牌的 值 。如果两张卡牌的值相同,则认为这一对卡牌 匹配 。 返回你必须拿起的最小连续卡牌数,以使在拿起的卡牌中有一对匹配的卡牌。如果无法得到一对匹配的卡牌,返回 -1 。 示例 1: 输入: cards = [3,4,2,3,…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

我们初始化答案为 ,遍历数组,对于每个数字 ,如果 存在,则表示 有一对匹配卡牌,此时更新答案为 $\textit{ans} = \min(\textit{ans}, i - \textit{last}[x] + 1)$,最后如果答案为 ,则返回 ,否则返回答案。 时间复杂度 ,空间复杂度 。其中 为数组长度。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 cards ,其中 cards[i] 表示第 i 张卡牌的 。如果两张卡牌的值相同,则认为这一对卡牌 匹配

返回你必须拿起的最小连续卡牌数,以使在拿起的卡牌中有一对匹配的卡牌。如果无法得到一对匹配的卡牌,返回 -1

 

示例 1:

输入:cards = [3,4,2,3,4,7]
输出:4
解释:拿起卡牌 [3,4,2,3] 将会包含一对值为 3 的匹配卡牌。注意,拿起 [4,2,3,4] 也是最优方案。

示例 2:

输入:cards = [1,0,5,3]
输出:-1
解释:无法找出含一对匹配卡牌的一组连续卡牌。

 

提示:

  • 1 <= cards.length <= 105
  • 0 <= cards[i] <= 106
lightbulb

解题思路

方法一:哈希表

我们初始化答案为 ++\infty,遍历数组,对于每个数字 xx,如果 last[x]\textit{last}[x] 存在,则表示 xx 有一对匹配卡牌,此时更新答案为 ans=min(ans,ilast[x]+1)\textit{ans} = \min(\textit{ans}, i - \textit{last}[x] + 1),最后如果答案为 ++\infty,则返回 1-1,否则返回答案。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组长度。

1
2
3
4
5
6
7
8
9
10
class Solution:
    def minimumCardPickup(self, cards: List[int]) -> int:
        last = {}
        ans = inf
        for i, x in enumerate(cards):
            if x in last:
                ans = min(ans, i - last[x] + 1)
            last[x] = i
        return -1 if ans == inf else ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    They want you to notice that every valid answer is bounded by two equal values, not by an arbitrary expandable window.

  • question_mark

    They expect the shortest segment for a repeated value to come from its most recent previous index, not from the first time it appeared.

  • question_mark

    They are testing whether you can replace window simulation with a direct last-seen hash lookup on an array scan.

warning

常见陷阱

外企场景
  • error

    Using the first occurrence of a value instead of the most recent one, which misses shorter spans like the later 4-length window in [3,4,2,3,4,7].

  • error

    Building a full sliding window with counts and shrink steps, which adds complexity without helping this exact duplicate-span problem.

  • error

    Forgetting the +1 in j - i + 1, which undercounts the number of consecutive cards picked up.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return the actual start and end indices of the shortest pickup instead of only its length.

  • arrow_right_alt

    Find the longest consecutive pickup that still contains at least one matching pair.

  • arrow_right_alt

    Process streaming card arrivals and report the current minimum duplicate span after each new card.

help

常见问题

外企场景

必须拿起的最小连续卡牌数题解:数组·哈希·扫描 | LeetCode #2260 中等