-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path982-TriplesWithBitwiseANDEqualToZero.go
More file actions
89 lines (81 loc) · 2.21 KB
/
982-TriplesWithBitwiseANDEqualToZero.go
File metadata and controls
89 lines (81 loc) · 2.21 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
// 982. Triples with Bitwise AND Equal To Zero
// Given an integer array nums, return the number of AND triples.
// An AND triple is a triple of indices (i, j, k) such that:
// 0 <= i < nums.length
// 0 <= j < nums.length
// 0 <= k < nums.length
// nums[i] & nums[j] & nums[k] == 0, where & represents the bitwise-AND operator.
// Example 1:
// Input: nums = [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
// Example 2:
// Input: nums = [0,0,0]
// Output: 27
// Constraints:
// 1 <= nums.length <= 1000
// 0 <= nums[i] < 2^16
import "fmt"
func countTriplets(nums []int) int {
mx := 0
for _, v := range nums { // 找到最大值
if v > mx {
mx = v
}
}
n := 1
for n <= mx {
n <<= 1
}
cnt := make([]int, n)
for _, x := range nums {
for _, y := range nums {
cnt[x&y]++
}
}
res := 0
for _, num := range nums {
subset := num ^ (n - 1)
res += cnt[0]
for i := subset; i > 0; i = subset & (i - 1) {
res += cnt[i]
}
}
return res
}
func main() {
// Example 1:
// Input: nums = [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
fmt.Println(countTriplets([]int{2,1,3})) // 12
// Example 2:
// Input: nums = [0,0,0]
// Output: 27
fmt.Println(countTriplets([]int{0,0,0})) // 27
}