338. Counting Bits--LeetCode Record

本文介绍了一种高效算法,用于计算从0到指定整数范围内每个数的二进制表示中1的数量,并通过优化实现了更快的速度。

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
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值