338. Counting Bits--LeetCode Record

Tong_hdj發表於2016-07-05

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.

Example:
For num = 5 you should return [0,1,1,2,1,2].

Follow up:

It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

class Solution {
    func countBits(num: Int) -> [Int] {
        var result:[Int] = []
        for i in 0...num {
            switch i {
            case 0:
                result.append(0)
            case 1:
                result.append(1)
            case 2:
                result.append(1)
            default:
                let quotient = i / 2
                let remainder = i % 2
                if result.count > quotient && result.count > remainder {
                    result.append(result[quotient] + result[remainder])
                }else {
                    return []
                }
            }
        }
        return result
    }
}
上面的結果為56ms,剛剛看了看評論區的一個post,48ms,被虐了。總結一下。
  1. 沒有對相同情況的用例進行優化。我的程式碼特定對0、1和2的情況進行了特殊處理,但是討論區的樣例程式碼對0進行了特殊處理,把後續情況歸為一類
  2. 其次,使用了一個switch,感覺把自己坑了。。。

站在巨人的肩膀上,優化了4ms,結果44ms,估計是坑爹的明確了一下變數型別

class Solution {
    func countBits(num: Int) -> [Int] {
        if num == 0 {
            return [0]
        }
        var result:[Int] = [0,1]
        var i = 2
        while i <= num {
            let quotient = i >> 1
            let remainder = i % 2
            result.append(result[quotient] + result[remainder])
            i++
        }
        return result
    }
}

相關文章