[leetcode][898] Bitwise ORs of Subarrays

[898] Bitwise ORs of Subarrays

We have an array A of non-negative integers.

For every (contiguous) subarray B = [A[i], A[i+1], ..., A[j]] (with i <= j), we take the bitwise OR of all the elements in B, obtaining a result A[i] | A[i+1] | ... | A[j].

Return the number of possible results.  (Results that occur more than once are only counted once in the final answer.)

Example 1:

Input: [0]
Output: 1
Explanation:
There is only one possible result: 0.

Example 2:

Input: [1,1,2]
Output: 3
Explanation:
The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].
These yield the results 1, 1, 2, 1, 3, 3.
There are 3 unique values, so the answer is 3.

Example 3:

Input: [1,2,4]
Output: 6
Explanation:
The possible results are 1, 2, 3, 4, 6, and 7.

Note:

1 <= A.length <= 50000
0 <= A[i] <= 10^9

解析:

一开始题目理解错了,没仔细看题目,以为是找到有多少不同的子集。实际上是给定一个集合,取他的任意连续子集(注意是连续的,也就是如果子集中的元素位置是连续的在原集合中的位置也是连续的),算出所有元素的的位或,算出所有可能的结果,去掉相同的结果,得到所有可能结果的数量。

参考答案(自己没做出来):

class Solution {
    public int subarrayBitwiseORs(int[] A) {
        Set<Integer> res = new HashSet<>(), cur = new HashSet<>(), cur2;
        for (Integer i: A) {
            cur2 = new HashSet<>();
            cur2.add(i);
            for (Integer j: cur) cur2.add(i|j);
            res.addAll(cur = cur2);
        }
        return res.size();
    }
}

res存放最终结果,cur存放上次或运算的结果,cur2存放本次或运算的结果,首先cur2会将当前元素加入到set中,然后再遍历cur中的元素,再与当前的元素进行或运算,把结果加入到cur2,因为都是set,所以自动去重了,保存上次运算结果主要是保证了连续性,下一个元素直接与上一次运算的结果就OK了。

猜你喜欢

转载自www.cnblogs.com/ekoeko/p/9583913.html
今日推荐