LeetCode 题解工作台

计算 K 置位下标对应元素的和

给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。 请你用整数形式返回 nums 中的特定元素之 和 ,这些特定元素满足:其对应下标的二进制表示中恰存在 k 个置位。 整数的二进制表示中的 1 就是这个整数的 置位 。 例如, 21 的二进制表示为 10101 ,其中有 3 个置位。 …

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·结合·位运算·操作

bolt

答案摘要

我们直接遍历每个下标 ,判断其二进制表示中 的个数是否等于 ,如果等于则将其对应的元素累加到答案 中。 遍历结束后,返回答案即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·结合·位运算·操作 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的整数数组 nums 和一个整数 k

请你用整数形式返回 nums 中的特定元素之 ,这些特定元素满足:其对应下标的二进制表示中恰存在 k 个置位。

整数的二进制表示中的 1 就是这个整数的 置位

例如,21 的二进制表示为 10101 ,其中有 3 个置位。

 

示例 1:

输入:nums = [5,10,1,5,2], k = 1
输出:13
解释:下标的二进制表示是: 
0 = 0002
1 = 0012
2 = 0102
3 = 0112
4 = 1002 
下标 1、2 和 4 在其二进制表示中都存在 k = 1 个置位。
因此,答案为 nums[1] + nums[2] + nums[4] = 13 。

示例 2:

输入:nums = [4,3,2,1], k = 2
输出:1
解释:下标的二进制表示是: 
0 = 002
1 = 012
2 = 102
3 = 112
只有下标 3 的二进制表示中存在 k = 2 个置位。
因此,答案为 nums[3] = 1 。

 

提示:

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

解题思路

方法一:模拟

我们直接遍历每个下标 ii,判断其二进制表示中 11 的个数是否等于 kk,如果等于则将其对应的元素累加到答案 ansans 中。

遍历结束后,返回答案即可。

时间复杂度 O(n×logn)O(n \times \log n),其中 nn 是数组 numsnums 的长度。空间复杂度 O(1)O(1)

1
2
3
4
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)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if the candidate correctly handles the bit counting and edge cases.

  • question_mark

    Evaluate their approach to time and space optimization for larger arrays.

  • question_mark

    Look for a clean and efficient solution using bitwise operations over string manipulation.

warning

常见陷阱

外企场景
  • error

    Overcomplicating the solution by using string manipulations instead of bitwise operations.

  • error

    Forgetting to handle edge cases such as k = 0 or very large indices.

  • error

    Neglecting to optimize for large input sizes, which may cause time or space inefficiencies.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Modify the problem to sum values at indices with more than k set bits.

  • arrow_right_alt

    Consider variations where the indices with exactly k set bits need to meet additional conditions (e.g., even or odd numbers).

  • arrow_right_alt

    Instead of counting set bits, change the task to sum values at indices where the binary representation has exactly n 1's and n 0's.

help

常见问题

外企场景

计算 K 置位下标对应元素的和题解:数组·结合·位运算·操作 | LeetCode #2859 简单