[LeetCode] Bitwise ORs of Subarrays
阿新 • • 發佈:2018-11-15
1、題目
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
2、分析
這個題出在動態規劃的欄目裡,一開始想了半天如何遞推,最後抱著試一試的心態暴力了以下,結果過了。
由於是運算,將整個陣列一個一個或起來的結果一定是所有子串的或運算結果中最大的一個。我們可以事先將整個最大結果記錄下來。然後開始暴力求接,遍歷所有可能的子串,求出他們或運算的結果,最終返回不同的結果的個數。其中在計算以下標i開頭的所有子串的或運算結果時,如果已經達到了最大值,則以i開頭的子串的情況就可以結束了,因為就算再延長j,或運算的結果也不會再改變了。去重的話直接使用set來實現。
3、程式碼
class Solution {
public:
int subarrayBitwiseORs(vector<int>& A) {
set<int> result;
int s = A.size();
int maxx=0,temp=0;
for(int i=0;i<s;i++)
{
result.insert(A[i]);
temp|=A[i];
result.insert(temp);
if(temp>maxx) maxx = temp;
}
for(int i=0;i<s;i++)
{
int n = A[i];
for(int j=i+1;j<s;j++)
{
n |= A[j];
result.insert(n);
if(n==maxx) break;
}
}
return result.size();
}
};