LeetCode 题解工作台

按位与为零的三元组

给你一个整数数组 nums ,返回其中 按位与三元组 的数目。 按位与三元组 是由下标 (i, j, k) 组成的三元组,并满足下述全部条件: 0 0 0 nums[i] & nums[j] & nums[k] == 0 ,其中 & 表示按位与运算符。 示例 1: 输入: nums = [2,1,3…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

困难 · 数组·哈希·扫描

bolt

答案摘要

我们可以先枚举任意两个数 和 ,用哈希表或数组 统计它们的按位与结果 $x \& y$ 出现的次数。 然后我们枚举 和 的按位与结果 ,再枚举 ,如果 $xy \& z = 0$,则将 的值加入答案。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums ,返回其中 按位与三元组 的数目。

按位与三元组 是由下标 (i, j, k) 组成的三元组,并满足下述全部条件:

  • 0 <= i < nums.length
  • 0 <= j < nums.length
  • 0 <= k < nums.length
  • nums[i] & nums[j] & nums[k] == 0 ,其中 & 表示按位与运算符。
 

示例 1:

输入:nums = [2,1,3]
输出:12
解释:可以选出如下 i, j, k 三元组:
(i=0, j=0, k=1) : 2 & 2 & 1
(i=0, j=1, k=0) : 2 & 1 & 2
(i=0, j=1, k=1) : 2 & 1 & 1
(i=0, j=1, k=2) : 2 & 1 & 3
(i=0, j=2, k=1) : 2 & 3 & 1
(i=1, j=0, k=0) : 1 & 2 & 2
(i=1, j=0, k=1) : 1 & 2 & 1
(i=1, j=0, k=2) : 1 & 2 & 3
(i=1, j=1, k=0) : 1 & 1 & 2
(i=1, j=2, k=0) : 1 & 3 & 2
(i=2, j=0, k=1) : 3 & 2 & 1
(i=2, j=1, k=0) : 3 & 1 & 2

示例 2:

输入:nums = [0,0,0]
输出:27

 

提示:

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] < 216
lightbulb

解题思路

方法一:枚举 + 计数

我们可以先枚举任意两个数 xxyy,用哈希表或数组 cntcnt 统计它们的按位与结果 x&yx \& y 出现的次数。

然后我们枚举 xxyy 的按位与结果 xyxy,再枚举 zz,如果 xy&z=0xy \& z = 0,则将 cnt[xy]cnt[xy] 的值加入答案。

最后返回答案即可。

时间复杂度 O(n2+n×M)O(n^2 + n \times M),空间复杂度 O(M)O(M),其中 nn 是数组 numsnums 的长度;而 MM 是数组 numsnums 中的最大值,本题中 M216M \leq 2^{16}

1
2
3
4
5
class Solution:
    def countTriplets(self, nums: List[int]) -> int:
        cnt = Counter(x & y for x in nums for y in nums)
        return sum(v for xy, v in cnt.items() for z in nums if xy & z == 0)
speed

复杂度分析

指标
时间complexity depends on the approach: brute force is O(n^3), hash map pairwise computation is O(n^2 + n*2^16) in worst case, and bitmask optimization leverages the 2^16 bound to stay efficient. Space complexity is O(n^2) for pairwise storage or O(2^16) for bitmask counts.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate immediately considers the high n^3 brute force and mentions performance issues.

  • question_mark

    Candidate references bit manipulation and hash tables to reduce redundant computation.

  • question_mark

    Candidate evaluates value constraints to optimize for possible masks and avoids unnecessary nested loops.

warning

常见陷阱

外企场景
  • error

    Attempting direct triple nested loops on large arrays, causing TLE.

  • error

    Forgetting that indices can repeat, leading to undercounting.

  • error

    Ignoring the 2^16 constraint, missing bitmask-based optimizations.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count quadruples with bitwise AND zero instead of triples.

  • arrow_right_alt

    Return all valid triples instead of just the count.

  • arrow_right_alt

    Modify to count AND triples for a target value other than zero.

help

常见问题

外企场景

按位与为零的三元组题解:数组·哈希·扫描 | LeetCode #982 困难