↓快轉到主要內容
  1. LeetCode/

LeetCode 3843: First Element with Unique Frequency

·1 分鐘· ·
LeetCode Medium Hash-Table Counting Array
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2026-02-16

  • 提交紀錄:Accepted(一次通過)

解題思路
#

兩層計數(Hash Table 模板一):

  • cnt:值 -> 次數。
  • freq_of_freq:次數 -> 有幾個不同的值是這個次數。

「次數唯一」就是 freq_of_freq[cnt[x]] == 1。要第一個,就照原陣列由左到右找。

我的解法
#

class Solution:
    def firstUniqueFreq(self, nums: List[int]) -> int:
        cnt = Counter(nums)
        freq_of_freq = Counter(cnt.values())
        for x in nums:
            if freq_of_freq[cnt[x]] == 1:
                return x
        return -1

複雜度
#

時間 O(n),空間 O(n)。

要特別避免的錯誤
#

  • 「第一個」是照原陣列的順序,不是照 cnt 的順序。

面試口說整理
#

我先數每個值的次數,再數每種次數有幾個值。由左到右掃原陣列,第一個次數只對應到一個值的就是答案。時間 O(n)。

相關文章

LeetCode 923: 3Sum With Multiplicity
·3 分鐘
LeetCode Medium Two-Pointers Sorting Hash-Table Counting Array
LeetCode 923 解題筆記:排序後固定第一個數、對撞指針找另外兩個;兩端值相同時用組合數一次算完,不同時把兩端各自的重複數相乘
LeetCode 3679: Minimum Discards to Balance Inventory
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Simulation Counting Array
LeetCode 3679 解題筆記:規則已經決定哪些要丟,直接模擬;長度 w 的視窗只計算「留下來」的到貨,被丟掉的離開視窗時不能再扣
LeetCode 1814: Count Nice Pairs in an Array
·1 分鐘
LeetCode Medium Array Hash-Table Math Counting
LeetCode 1814 解題筆記:把條件移項成 nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]),按這個值分組數 pair,記得取模
LeetCode 3071: Minimum Operations to Write the Letter Y on a Grid
·1 分鐘
LeetCode Medium Array Hash-Table Matrix Counting
LeetCode 3071 解題筆記:分別數 Y 上和 Y 外每個值的次數,枚舉 Y 的值 a 和背景的值 b(a != b),取最少要改的格子數
LeetCode 229: Majority Element II
·1 分鐘
LeetCode Medium Array Hash-Table Sorting Counting
LeetCode 229 解題筆記:超過 n / 3 的數最多兩個;Boyer-Moore 維護兩個候選人,最後再掃一次確認次數
LeetCode 3719: Longest Balanced Subarray I
·1 分鐘
LeetCode Medium Hash-Table Prefix-Sum Segment-Tree Array
LeetCode 3719 解題筆記:n 只有 1500,固定左端點往右擴,用兩個集合增量維護不同的奇數和偶數