Leetcode # 2859. Sum of Values at Indices With K Set Bits

Problem

https://leetcode.com/contest/weekly-contest-363/problems/sum-of-values-at-indices-with-k-set-bits/

Solution

Time Complexity: O(len(nums) * log(max(nums)))
Space Complexity: O(1)
(The input and output generally do not count towards the space complexity.)

class Solution:
  def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int:
    result = 0
    for i, num in enumerate(nums):
      set_bits = 0
      while i > 0:
        set_bits += i % 2
        i //= 2
      result += num if set_bits == k else 0
    return result

使用  bin() 來精簡

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)

 

Last Updated on 2023/09/19 by A1go

目錄
Bitnami