898. Bitwise ORs of Subarrays

88 篇文章 0 订阅
5 篇文章 0 订阅

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)
    

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值