版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjucor/article/details/86668130
Given an array of integers A
, find the number of triples of indices (i, j, k) such that:
0 <= i < A.length
0 <= j < A.length
0 <= k < A.length
A[i] & A[j] & A[k] == 0
, where&
represents the bitwise-AND operator.
Example 1:
Input: [2,1,3]
Output: 12
Explanation: We could choose the following i, j, k triples:
(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
Note:
1 <= A.length <= 1000
0 <= A[i] < 2^16
思路:直接暴力遍历一遍两两求&的count,然后再和原始数组遍历一下
讨论去有用DP,但是复杂度跟上面暴力差不多https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/discuss/226721/Java-DP-O(3-*-216-*-n)-time-O(n)-space
也有O(n log n)的解法:
https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/discuss/226832/Fastest-Solution-Using-Fast-Walsh-Hadamard-Transform-32ms
class Solution(object):
def countTriplets(self, A):
"""
:type A: List[int]
:rtype: int
"""
cnt = {}
for i in A:
for j in A:
a=i&j
cnt[a] = cnt.get(a, 0)+1
res=0
for i in A:
for j in cnt:
if i&j==0: res+=cnt[j]
return res