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

LeetCode 2859: Sum of Values at Indices With K Set Bits

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

基本資料
#

難易度: easy 第一次嘗試:2023-09-17

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

解題思路
#

對每個 index i 數 bin(i) 裡 1 的個數(Bit Manipulation),剛好是 k 就把 nums[i] 加進答案。

我的解法
#

class Solution:
    def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int:
        return sum(x for i, x in enumerate(nums) if bin(i).count("1") == k)

複雜度
#

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

要特別避免的錯誤
#

  • 判斷的是 index,不是 nums[i]。

面試口說整理
#

我對每個 index 數它二進位裡 1 的個數,剛好是 k 就把那個位置的值加起來。時間 O(n log n)。

相關文章

LeetCode 136: Single Number
·1 分鐘
LeetCode Easy Array Bit-Manipulation
LeetCode 136 解題筆記:x ^ x = 0、x ^ 0 = x,把所有數 XOR 起來,出現兩次的互相抵消,剩下的就是答案
LeetCode 1018: Binary Prefix Divisible By 5
·1 分鐘
LeetCode Easy Array Bit-Manipulation
LeetCode 1018 解題筆記:前綴每多一位就是 x = 2x + bit,只要保留 x mod 5,數字不會變大
LeetCode 832: Flipping an Image
·1 分鐘
LeetCode Easy Array Two-Pointers Bit-Manipulation Matrix
LeetCode 832 解題筆記:每一列先左右反轉再把 0、1 互換;可以用左右指針同時做
LeetCode 645: Set Mismatch
·1 分鐘
LeetCode Easy Array Hash-Table Bit-Manipulation Sorting
LeetCode 645 解題筆記:用總和算:missing = 1..n 的和 - set 的和,duplicate = 陣列總和 - set 的和
LeetCode 1413: Minimum Value to Get Positive Step by Step Sum
·1 分鐘
LeetCode Easy Array Prefix-Sum
LeetCode 1413 解題筆記:起始值加上每個前綴和都要 >= 1,所以起始值是 max(1, 1 - 最小前綴和)
LeetCode 1480: Running Sum of 1d Array
·1 分鐘
LeetCode Easy Array Prefix-Sum
LeetCode 1480 解題筆記:前綴和的定義,每一格加上前一格