题目链接
题目描述
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.)
Example1
Input: [0]
Output: 1
Explanation:
There is only one possible result: 0.
Example2
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.
Example3
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
代码一:
使用暴力求解,O(N2),时间254ms
class Solution {
public int subarrayBitwiseORs(int[] A) {
if(A == null || A.length == 0) {
return 0;
}
Set<Integer> set = new HashSet<>();
int max = 0;
for(int i = 0; i < A.length; i++) {
set.add(A[i]);
max |= A[i];
set.add(max);
}
for(int i = 0; i < A.length; i++) {
for(int j = i+1, n = 0; j < A.length; j++) {
n |= A[j];
set.add(n);
if(n == max) {
break;
}
}
}
return set.size();
}
}
代码二
该方法使用求解子集时的另一种方法,
class Solution {
public int subarrayBitwiseORs(int[] A) {
if(A == null || A.length == 0) {
return 0;
}
Set<Integer> set = new HashSet<>();
int max = 0;
for(int i = 0; i < A.length; i++) {
set.add(A[i]);
max |= A[i];
set.add(max);
}
for(int i = 0; i < A.length; i++) {
for(int j = i+1, n = 0; j < A.length; j++) {
n |= A[j];
set.add(n);
if(n == max) {
break;
}
}
}
return set.size();
}
}
这个是在disucuss里边找到的一个比较好的解释链接
我摘抄下来如下:
假设一个数组为 [001, 011, 100, 110, 101] (in binary).
所有的子集则如下:(可以自己在本子上画一下二叉树,就能发现这个规律)
[001]
[001 011] [011]
[001 011 100] [011 100] [100]
[001 011 100 110] [011 100 110] [100 110] [110]
[001 011 100 110 101] [011 100 110 101] [100 110 101] [110 101] [101]
In each line, we add a new number to each array of the previous line.
在每一行,我们都能发现,当前行是在它上一行的每个元素上添加了一个新的数,假设这是第i行,就是增加A[i]
对每一行坐或运算,则得到结果如下:
001
011 011
111 111 100
111 111 110 110
111 111 111 111 101
时间复杂度是o(n2),TLE
当删除了重复的之后,变成下面的。
001
011
111 100
111 110
111 101
在行t,任意的两个数t[i]和t[j](i < j), t[i] 一定比t[j]多一个1,因此,每行不会超过32个数,因此复杂度是O(kN),这里K是输入数字bit位的最大值。在该问题中是32。