1. 程式人生 > >JavaScript刷LeetCode -- 898. Bitwise ORs of Subarrays

JavaScript刷LeetCode -- 898. Bitwise ORs of Subarrays

一、題目

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.)

0 <= A[i] <= 10^9

二、題目大意

給定一個非負整數陣列A,從A中找出所有子陣列,將每個子陣列中的元素進行位或操作,求出互相不相同的元素有多少個?

三、解題思路

首先可以採用一波暴力解法:

const subarrayBitwiseORs = (A) => {

  const max = A.length
  const x = new Set()

  for (let i = 0; i < max; i++) {
    let item = A[i]
    x.add(item)
    for (let j = i + 1; j < max; j++) {
      item = item | A[j]
      x.add(item)
    }
  }
  return x.size
}

意料之中的超時,這時我們需要思考的就是如何將O(n^2)轉化為O(n),對於A[i]最多可以用30位表示,那麼如果通過set記錄前一次集合,那麼最多就是30個元素,利用這一點就可以將時間複雜度降低為O(30n):

四、程式碼實現

const subarrayBitwiseORs1 = (A) => {

  let cur = new Set()
  const ans = new Set()

  for (let i = 0; i < A.length; i++) {
    const item = A[i]
    const x = new Set()
    for (let e of cur.values()) {
      x.add(e | item)
    }
    x.add(item)
    cur = x
    for (let sub of cur.values()) {
      ans.add(sub)
    }
  }

  return ans.size
}

如果本文對您有幫助,歡迎關注我的微信公眾號【超愛敲程式碼】,為您推送更多內容,ε=ε=ε=┏(゜ロ゜;)┛。