[Swift]LeetCode982. 按位與爲零的三元組 | Triples with Bitwise AND Equal To Zero

原文地址:http://www.javashuo.com/article/p-zpapsfcy-md.html html

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:spa

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:code

  1. 1 <= A.length <= 1000
  2. 0 <= A[i] < 2^16

給定一個整數數組 A,找出索引爲 (i, j, k) 的三元組,使得:htm

  • 0 <= i < A.length
  • 0 <= j < A.length
  • 0 <= k < A.length
  • A[i] & A[j] & A[k] == 0,其中 & 表示按位與(AND)操做符。 

示例:blog

輸入:[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. 1 <= A.length <= 1000
  2. 0 <= A[i] < 2048

9888msip

 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 }
相關文章
相關標籤/搜索