leetcode 898

问题

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:

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

Example 2:

1
2
3
4
5
6
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:

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

Note:

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

分析

遍历输入数组,对于每一个 a[i],考虑以 a[i] 为末尾的所有子数字情况,则有 a[i] 自己独立为一个字数组,或者a[i] 加入到每一个以a[i-1],为结尾的字数组中。因为覆盖关系,每次操作最多只会处理30个数。因此,时间复杂度是 $O(30N)$。https://leetcode.com/problems/bitwise-ors-of-subarrays/discuss/165881/C%2B%2BJavaPython-O(30N)

代码

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int subarrayBitwiseORs(vector<int>& A) {
unordered_set<int> ans, cur, cur2;
for (int i: A) {
cur = {i};
for (int j: cur2) cur.insert(i|j);
for (int j: cur2 = cur) ans.insert(j);
}
return ans.size();
}
};