Leetcode 982. Triples with Bitwise AND Equal To Zero

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/M_sdn/article/details/86665174

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

蛮力法加一点点优化 

public int countTriplets(int[] A) {
        int count = 0;
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        int N = A.length;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                int k = A[i] & A[j];
                hashMap.put(k, hashMap.getOrDefault(k, 0) +1);
            }
        }
        for (int i = 0; i < N; i++) {
            for (int k :hashMap.keySet()) {
                if ((A[i] & k) == 0) {
                    count += hashMap.get(k);
                }
            }
        }
        return count;
}

猜你喜欢

转载自blog.csdn.net/M_sdn/article/details/86665174
今日推荐