★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-ayxbyynt-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
We have an array A
of non-negative integers.git
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]
.github
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:app
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:spa
Input: [1,2,4]
Output: 6 Explanation: The possible results are 1, 2, 3, 4, 6, and 7.
Note:code
1 <= A.length <= 50000
0 <= A[i] <= 10^9
咱們有一個非負整數數組 A
。orm
對於每一個(連續的)子數組 B = [A[i], A[i+1], ..., A[j]]
( i <= j
),咱們對 B
中的每一個元素進行按位或操做,得到結果 A[i] | A[i+1] | ... | A[j]
。htm
返回可能結果的數量。 (屢次出現的結果在最終答案中僅計算一次。)
示例 1:
輸入:[0] 輸出:1 解釋: 只有一個可能的結果 0 。
示例 2:
輸入:[1,1,2] 輸出:3 解釋: 可能的子數組爲 [1],[1],[2],[1, 1],[1, 2],[1, 1, 2]。 產生的結果爲 1,1,2,1,3,3 。 有三個惟一值,因此答案是 3 。
示例 3:
輸入:[1,2,4] 輸出:6 解釋: 可能的結果是 1,2,3,4,6,以及 7 。
提示:
1 <= A.length <= 50000
0 <= A[i] <= 10^9
1 class Solution { 2 func subarrayBitwiseORs(_ A: [Int]) -> Int { 3 var res:Set<Int> = Set<Int>() 4 var cur:Set<Int> = Set<Int>() 5 for i in A 6 { 7 var cur2:Set<Int> = Set<Int>() 8 cur2.insert(i) 9 res.insert(i) 10 for j in cur 11 { 12 cur2.insert(i|j) 13 res.insert(i|j) 14 } 15 cur = cur2 16 } 17 return res.count 18 } 19 }
1312ms
1 class Solution { 2 func subarrayBitwiseORs(_ A: [Int]) -> Int { 3 if A.count == 0 { 4 return 0 5 } 6 7 if A.count == 1 { 8 return 1 9 } 10 var total = Set<Int>() 11 var one: Set = [A[0]] 12 total.insert(A[0]) 13 for i in 1..<A.count { 14 var next = Set<Int>() 15 one.insert(0) 16 for item in one { 17 let t = item|A[i] 18 next.insert(t) 19 total.insert(t) 20 } 21 one = next 22 } 23 return total.count 24 } 25 }
1756ms
1 class Solution { 2 func subarrayBitwiseORs(_ A: [Int]) -> Int { 3 var res = [Int]() 4 var current = Set<Int>() 5 var temp = Set<Int>() 6 for num in A { 7 temp.removeAll() 8 for x in current { 9 temp.insert(num | x) 10 } 11 temp.insert(num) 12 current = temp 13 res.append(contentsOf: current) 14 } 15 return Set(res).count 16 } 17 }
1784ms
1 class Solution { 2 func subarrayBitwiseORs(_ A: [Int]) -> Int { 3 var res = Set<Int>(), last = Set<Int>(), cur = Set<Int>() 4 for i in A { 5 cur = Set<Int>([i]) 6 for j in last { 7 cur.insert(i|j) 8 } 9 last = cur 10 res.formUnion(cur) 11 } 12 return res.count 13 } 14 }