338. Counting Bits--LeetCode Record
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
}
}
相關文章
- GCD CountingGC
- 計數排序 - Counting Sort排序
- react-recordReact
- Automatic Reference Counting-SwiftSwift
- Daily record-SeptemberAI
- python ref counting based garbage collectionPython
- iOS中的Reference Counting詳解iOS
- UVa 1225 - Digit CountingGit
- 【LeetCode】Counting Bits(338)LeetCode
- LeetCode 338 Counting BitsLeetCode
- Codeforces 954H Path Counting
- 實戰 Java 16 值型別 Record - 2. Record 的基本用法Java型別
- pl/sql record 詳解SQL
- delete duplication record in sql serverdeleteSQLServer
- projecteuler---->problem=19----Counting SundaysProject
- Digit Counting uva1225Git
- CF1919E Counting Prefixes
- Java 16 新特性:record類Java
- Erlang中的Record詳解
- 淺析 record 使用場景
- Record It for Mac錄屏軟體Mac
- Java 21 新特性:Record PatternsJava
- 脫離rails 使用Active RecordAI
- Homework record-Simple sorting
- gorm忽略報錯: record not foundGoORM
- leetcode [python] 【338】Counting BitsLeetCodePython
- LeetCode 第 338 題 (Counting Bits)LeetCode
- Python演算法:Counting 101Python演算法
- Warning:dns_get_record():AtemporaryservererroroccurredDNSServerError
- Record for Individual Project ( Word frequency program )Project
- Using Statspack to Record Explain Plan DetailsAI
- record:記錄(帶名元組)
- 不好分類的好題Record
- Camera List Record - 120
- 如何處理 No DMARC Record Found 問題
- supremum pseudo-record鎖影響REM
- Ext.js4.2.1 Ext.data.RecordJS
- 轉:Oracle 解鎖Record is locked by another useOracle