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,被虐了。总结一下。
- 没有对相同情况的用例进行优化。我的代码特定对0、1和2的情况进行了特殊处理,但是讨论区的样例代码对0进行了特殊处理,把后续情况归为一类
- 其次,使用了一个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
}
}