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

LeetCode 3833: Count Dominant Indices

·1 分鐘· ·
LeetCode Easy Array Enumeration
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2026-02-08

  • 提交紀錄:Wrong Answer → Accepted

解題思路
#

nums[i] 要大於右邊元素的平均(不包含自己)。從右往左掃,維護右邊的總和和個數(Array 模板三)。比較平均時改成乘法:nums[i] > s / c 等於 nums[i] * c > s,避免浮點數和整數除法的問題。最後一個元素右邊沒有東西,不算。

我的嘗試
#

第一版有兩個問題:平均用 // 整數除法,而且第 i 個的平均包含了自己。例如 [4, 3, 5, 4]:只有 5 > 4,答案 1;這版回傳 2。改成 /、並且跟 i + 1 開始的後綴平均比較就 AC 了。

正確解法
#

class Solution:
    def dominantIndices(self, nums: List[int]) -> int:
        n, suffix, res = len(nums), 0, 0
        for i in range(n - 1, -1, -1):
            cnt = n - 1 - i
            if cnt and nums[i] * cnt > suffix:
                res += 1
            suffix += nums[i]
        return res

複雜度
#

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

要特別避免的錯誤
#

  • 平均不包含自己。
  • 用整數除法會把平均往下取整,比較就錯了;改成乘法最安全。

面試口說整理
#

我從右往左維護右邊的總和,每個位置比較自己乘上右邊個數是否大於右邊總和,等於比平均大,而且不用浮點數。時間 O(n)。

相關文章

LeetCode 2094: Finding 3-Digit Even Numbers
·1 分鐘
LeetCode Easy Hash-Table Enumeration Array
LeetCode 2094 解題筆記:反過來枚舉 100 到 998 的偶數,檢查需要的每個數字次數夠不夠;Counter 相減只留正數
LeetCode 976: Largest Perimeter Triangle
·1 分鐘
LeetCode Easy Math Greedy Sorting Geometry Array
LeetCode 976 解題筆記:排序後,從最大的開始看連續的三條邊,a + b > c 第一次成立就是最大周長
LeetCode 2122: Recover the Original Array
·2 分鐘
LeetCode Hard Two-Pointers Sorting Hash-Table Enumeration Array
LeetCode 2122 解題筆記:最小的數一定在 lower,枚舉它的配對決定 k;排序後用兩個指針把每個最小的未配對數配給 +2k 的數
LeetCode 2200: Find All K-Distant Indices in an Array
·1 分鐘
LeetCode Easy Two-Pointers Array
LeetCode 2200 解題筆記:每個 key 往左右各延伸 k 格,用一個指針記住已經輸出到哪裡,避免重疊的區間重複輸出
LeetCode 3637: Trionic Array I
·1 分鐘
LeetCode Easy Array
LeetCode 3637 解題筆記:一個 index 依序走過上坡、下坡、上坡,三段都要非空而且剛好走到最後
LeetCode 1304: Find N Unique Integers Sum up to Zero
·1 分鐘
LeetCode Easy Math Array
LeetCode 1304 解題筆記:放 1..n/2 和它們的相反數,兩兩抵銷;n 是奇數時再加一個 0