forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
triples-with-bitwise-and-equal-to-zero.py
55 lines (47 loc) · 1.3 KB
/
triples-with-bitwise-and-equal-to-zero.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Time: O(nlogn), n is the max of A
# Space: O(n)
import collections
# Reference: https://blog.csdn.net/john123741/article/details/76576925
# FWT solution
class Solution(object):
def countTriplets(self, A):
"""
:type A: List[int]
:rtype: int
"""
def FWT(A, v):
B = A[:]
d = 1
while d < len(B):
for i in xrange(0, len(B), d << 1):
for j in xrange(d):
B[i+j] += B[i+j+d] * v
d <<= 1
return B
k = 3
n, max_A = 1, max(A)
while n <= max_A:
n *= 2
count = collections.Counter(A)
B = [count[i] for i in xrange(n)]
C = FWT(map(lambda x : x**k, FWT(B, 1)), -1)
return C[0]
# Time: O(n^3), n is the length of A
# Space: O(n^2)
import collections
class Solution2(object):
def countTriplets(self, A):
"""
:type A: List[int]
:rtype: int
"""
count = collections.defaultdict(int)
for i in xrange(len(A)):
for j in xrange(len(A)):
count[A[i]&A[j]] += 1
result = 0
for k in xrange(len(A)):
for v in count:
if A[k]&v == 0:
result += count[v]
return result