⚡Flashcard Drill➔
NeetCode #13LC-1133EasyArrays & HashingNC Algo100
← Back to All Problems

#13 · #1133 · Largest Unique Number(最大唯一数)

📌 Problem Statement & Constraints

Given an integer array nums, return the largest integer that only occurs once. If no integer occurs exactly once, return -1. Constraints: 1 <= nums.length <= 2000, 0 <= nums[i] <= 1000.

💡 Core Algorithmic Approaches

  1. Count the frequency of every value with a hash map.
  2. Scan the frequency map and keep the maximum key whose count is exactly 1.
  3. Initialise the answer to -1 so the no-unique-value case needs no special handling.
  4. An alternative is to sort and check neighbours, but counting is O(n) and simpler.

💻 Benchmark Python3 Implementation

class Solution:
    def largestUniqueNumber(self, nums: List[int]) -> int:
        from collections import Counter
        cnt = Counter(nums)
        res = -1                           # default when nothing is unique
        for v, c in cnt.items():
            if c == 1:
                res = max(res, v)
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass to count, one pass over the distinct values (at most n).
💾 Space Complexity
O(k) for the counter, where k is the number of distinct values.

⚠️ Interview Pitfalls & Follow-ups

  • Returning 0 when nothing is unique: the answer must be -1, and 0 is a legitimate unique value in the input range.
  • Sorting and scanning neighbours: O(n log n) and requires care with runs longer than 2.
  • Only tracking the maximum seen value: you must first know the frequency, so a two-phase approach is needed.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

最大唯一数

给你一个整数数组 nums,找出并返回其中只出现一次的最大整数。如果不存在只出现一次的数字,返回 -1。约束:1 ≤ nums.length ≤ 2000;0 ≤ nums[i] ≤ 1000。

核心要点

  • 哈希计数(标准解) :用 Counter 统计每个数字的出现次数,遍历计数表,在所有计数为 1 的数字中取最大值。
  • 排序后扫描(替代解) :升序排序后从右往左找第一个与左右邻居都不相同的元素。时间 O(n log n),不如计数法。
  • 布尔数组(利用值域小) :nums[i] ≤ 1000,可开长度 1001 的数组记录「出现次数」,再用一个布尔数组标记「出现超过一次」。
  • 为什么不能直接取 set 的最大值 :set 只去重,无法区分「出现一次」与「出现多次」,必须结合计数。

常见陷阱

  • 用 set 直接取 max : max(set(nums)) 返回的是「出现过的最大数」,而不是「只出现一次的最大数」。这是最常见的错误。
  • 初始值设为 0 :nums[i] ≥ 0,若初始值设为 0,当答案确实不存在时返回 0 而非 -1,与题意不符。应初始化为 -1。
  • 误以为需要排序 :排序解法虽然正确但为 O(n log n),在本题的计数法面前是劣解。

参考实现

from collections import Counter

class Solution:
    def largestUniqueNumber(self, nums: list[int]) -> int:
        cnt = Counter(nums)
        ans = -1
        for v, c in cnt.items():
            if c == 1 and v > ans:
                ans = v
        return ans

# 替代写法:在出现一次的集合里取最大值
# once = {v for v, c in Counter(nums).items() if c == 1}
# return max(once) if once else -1