898. Bitwise ORs of Subarrays

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

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. 1 <= A.length <= 50000
  2. 0 <= A[i] <= 10^9

直接求出以index为结尾的结果有哪些!而且复杂度最大O(30N)!

因为是或运算嘛,比如从i开始,j越大,或的结果就越大(或者相等),而且之前bit数为1的,j变大后也一定是为1的,所以你最多也就新增30个数

自己想到了位运算+OR的特殊性,但就是没有想通啊

Intuition:
Assume B[i][j] = A[i] | A[i+1] | ... | A[j]
Hash set cur stores all wise B[0][i]B[1][i]B[2][i]B[i][i].

When we handle the A[i+1], we want to update cur
So we need operate bitwise OR on all elements in cur.
Also we need to add A[i+1] to cur.

In each turn, we add all elements in cur to res.

Time Complexity:
O(30N)

Normally this part is easy.
But for this problem, time complexity matters a lot.

The solution is straight forward,
while you may worry about the time complexity up to O(N^2)
However, it's not the fact.
This solution has only O(30N)

The reason is that, B[0][i] >= B[1][i] >= ... >= B[i][i].
B[0][i] covers all bits of B[1][i]
B[1][i] covers all bits of B[2][i]
....

There are at most 30 bits for a positive number 0 <= A[i] <= 10^9.
So there are at most 30 different values for B[0][i]B[1][i]B[2][i], ..., B[i][i].
Finally cur.size() <= 30 and res.size() <= 30 * A.length()

In a worst case, A = {1,2,4,8,16,..., 2 ^ 29}
And all B[i][j] are different and res.size() == 30 * A.length()

class Solution:
    def subarrayBitwiseORs(self, a):
        """
        :type A: List[int]
        :rtype: int
        """
        s1=set([a[0]])
        res=set(a)
        for i in range(1,len(a)):
            s2=set()
            for t in s1:
                s2.add(t|a[i])
            s2.add(a[i])
            for t in s2: res.add(t)
            s1=s2
        return len(res)
    

猜你喜欢

转载自blog.csdn.net/zjucor/article/details/82314006
今日推荐