4

leetcode 982. 按位与为零的三元组

 3 years ago
source link: https://iamxcb.com/leetcode-982.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

leetcode 982. 按位与为零的三元组

发表于 2019-07-11

| 0

| 阅读次数:

给定一个整数数组 A,找出索引为 (i, j, k) 的三元组,使得:

  1. 0 <= i < A.length
  2. 0 <= j < A.length
  3. 0 <= k < A.length
  4. 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. 1 <= A.length <= 1000
  2. 0 <= A[i] < 2^16

分两步,先计算 A[i] & A[j] 保存出现的次数,再计算 (A[i] & A[j]) & A[k] 判断是否为零

示例代码(go)

func countTriplets(A []int) int {
res, n := 0, len(A)
hash := make(map[int]int)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
hash[A[i] & A[j]]++
}
}
for key, count := range hash {
for k := 0; k < n; k++ {
if key & A[k] == 0 {
res += count
}
}
}
return res
}
表情 | 预览
Code 1: The app is disabled for violation of user agreement.
Powered By Valine
v1.3.9

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK