返回介绍

solution / 2800-2899 / 2859.Sum of Values at Indices With K Set Bits / README_EN

发布于 2024-06-17 01:02:59 字数 3984 浏览 0 评论 0 收藏 0

2859. Sum of Values at Indices With K Set Bits

中文文档

Description

You are given a 0-indexed integer array nums and an integer k.

Return _an integer that denotes the sum of elements in _nums_ whose corresponding indices have exactly _k_ set bits in their binary representation._

The set bits in an integer are the 1's present when it is written in binary.

  • For example, the binary representation of 21 is 10101, which has 3 set bits.

 

Example 1:

Input: nums = [5,10,1,5,2], k = 1
Output: 13
Explanation: The binary representation of the indices are: 
0 = 0002
1 = 0012
2 = 0102
3 = 0112
4 = 1002 
Indices 1, 2, and 4 have k = 1 set bits in their binary representation.
Hence, the answer is nums[1] + nums[2] + nums[4] = 13.

Example 2:

Input: nums = [4,3,2,1], k = 2
Output: 1
Explanation: The binary representation of the indices are:
0 = 002
1 = 012
2 = 102
3 = 112
Only index 3 has k = 2 set bits in its binary representation.
Hence, the answer is nums[3] = 1.

 

Constraints:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 105
  • 0 <= k <= 10

Solutions

Solution 1: Simulation

We directly traverse each index $i$, and check whether the number of $1$s in its binary representation is equal to $k$. If it is, we add the corresponding element to the answer $ans$.

After the traversal ends, we return the answer.

The time complexity is $O(n \times \log n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.

class Solution:
  def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int:
    return sum(x for i, x in enumerate(nums) if i.bit_count() == k)
class Solution {
  public int sumIndicesWithKSetBits(List<Integer> nums, int k) {
    int ans = 0;
    for (int i = 0; i < nums.size(); i++) {
      if (Integer.bitCount(i) == k) {
        ans += nums.get(i);
      }
    }
    return ans;
  }
}
class Solution {
public:
  int sumIndicesWithKSetBits(vector<int>& nums, int k) {
    int ans = 0;
    for (int i = 0; i < nums.size(); ++i) {
      if (__builtin_popcount(i) == k) {
        ans += nums[i];
      }
    }
    return ans;
  }
};
func sumIndicesWithKSetBits(nums []int, k int) (ans int) {
  for i, x := range nums {
    if bits.OnesCount(uint(i)) == k {
      ans += x
    }
  }
  return
}
function sumIndicesWithKSetBits(nums: number[], k: number): number {
  let ans = 0;
  for (let i = 0; i < nums.length; ++i) {
    if (bitCount(i) === k) {
      ans += nums[i];
    }
  }
  return ans;
}

function bitCount(n: number): number {
  let count = 0;
  while (n) {
    n &= n - 1;
    count++;
  }
  return count;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文