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

LeetCode 3917: Count Indices With Opposite Parity

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

基本資料
#

難易度: easy 第一次嘗試:2026-05-03

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

解題思路
#

每個位置 i 要數右邊有幾個 j 的奇偶跟 nums[i] 相反。從右往左掃,維護「右邊有幾個偶數、幾個奇數」(Array 模板三),每個位置直接查相反那一類的個數,再把自己加進去。

我的解法
#

class Solution:
    def countOppositeParity(self, nums: List[int]) -> List[int]:
        seen = [0, 0]                          # 右邊的偶數、奇數個數
        res = [0] * len(nums)
        for i in range(len(nums) - 1, -1, -1):
            p = nums[i] % 2
            res[i] = seen[1 - p]
            seen[p] += 1
        return res

我當時對每個 i 都往右掃一次,O(n²);範圍小所以也過了。

複雜度
#

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

要特別避免的錯誤
#

  • 算的是右邊的個數,所以要從右往左掃,先查答案、再把自己加進計數。

面試口說整理
#

我從右往左掃,記右邊有幾個偶數和奇數,每個位置的答案就是相反奇偶的個數,然後把自己加進去。時間 O(n)。

相關文章

LeetCode 3912: Valid Elements in an Array
·1 分鐘
LeetCode Easy Array
LeetCode 3912 解題筆記:比左邊全部大就是比前綴最大值大,比右邊全部大就是比後綴最大值大;兩個方向各掃一次再照原順序輸出
LeetCode 3903: Smallest Stable Index I
·1 分鐘
LeetCode Easy Prefix-Sum Array
LeetCode 3903 解題筆記:前綴最大值減後綴最小值 <= k 的第一個 index;後綴最小值先從右往左建好
LeetCode 3898: Find the Degree of Each Vertex
·1 分鐘
LeetCode Easy Graph Matrix Array
LeetCode 3898 解題筆記:鄰接矩陣第 i 列的 1 的個數就是頂點 i 的度數
LeetCode 3838: Weighted Word Mapping
·1 分鐘
LeetCode Easy Array String Simulation
LeetCode 3838 解題筆記:每個字的權重加總取 mod 26,再反向對應字母:0 -> z,也就是 chr(ord(‘z’) - r)
LeetCode 3379: Transformed Array
·1 分鐘
LeetCode Easy Array Simulation
LeetCode 3379 解題筆記:往右或往左走 nums[i] 步都可以寫成 nums[(i + nums[i]) % n];Python 的 % 對負數也回傳非負值
LeetCode 2540: Minimum Common Value
·1 分鐘
LeetCode Easy Two-Pointers Array
LeetCode 2540 解題筆記:兩個排序好的陣列各一個指針,比較小的那邊往前,第一次相等就是答案