[Swift Weekly Contest 121]LeetCode982. 按位與為零的三元組 | Triples with Bitwise AND Equal To Zero
阿新 • • 發佈:2019-01-27
提示 ret 元組 could nts func where family spa
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
給定一個整數數組 A
,找出索引為 (i, j, k) 的三元組,使得:
0 <= i < A.length
0 <= j < A.length
0 <= k < A.length
A[i] & A[j] & A[k] == 0
,其中&
表示按位與(AND)操作符。
示例:
輸入:[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
提示:
1 <= A.length <= 1000
0 <= A[i] < 2048
9888ms
1 class Solution { 2 func countTriplets(_ A: [Int]) -> Int { 3 var cnt:[Int] = [Int](repeating:0,count:65536) 4 for i in 0..<65536 5 { 6 for n in A 7 { 8 if(i&n)==0 9 { 10 cnt[i] += 1 11 } 12 } 13 } 14 15 var res:Int = 0 16 for a in A 17 { 18 for b in A 19 { 20 res += cnt[a&b] 21 } 22 } 23 return res 24 } 25 }
[Swift Weekly Contest 121]LeetCode982. 按位與為零的三元組 | Triples with Bitwise AND Equal To Zero