Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions 0338.Counting-Bits/memo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# 338. Counting Bits

## step1
4m ぐらい。hamming weightの問題の配列前計算の方法をまねた。計算量 O(n)。動的計画法である。

動的計画法を使わないと計算量は O(nlog n)になる。

しかし、実行速度自体は組み込み関数を使えばこの解法の方が速い。

Follow up もその旨が書かれている。

> It is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass?

## 他の人のコード
https://github.com/rihib/leetcode/pull/44

動的計画法だが考え方が異なる。自分のものは下一桁とそれ以外に分けていたが、これは上一桁とそれ以外に分けている。

> Rightmost set bitをunsetする方法
- x & (x - 1)
- x - (x & -x)

https://github.com/rihib/leetcode/blob/main/go/counting_bits.go
12 changes: 12 additions & 0 deletions 0338.Counting-Bits/step1_dp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Solution:
def countBits(self, n: int) -> list[int]:
if n == 0:
return [0]

result = [0] * (n + 1)

for i in range(n + 1):
result[i] = result[i >> 1] + (i & 1)

return result

9 changes: 9 additions & 0 deletions 0338.Counting-Bits/step1_naive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class Solution:
def countBits(self, n: int) -> list[int]:
result = [0] * (n + 1)

for i in range(n + 1):
result[i] = i.bit_count()

return result

17 changes: 17 additions & 0 deletions 0338.Counting-Bits/step2_dpv2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class Solution:
def countBits(self, n: int) -> list[int]:
if n == 0:
return [0]

result = [0] * (n + 1)
power_of_two = 1

for i in range(1, n + 1):
if i == power_of_two << 1:
result[i] = 1
power_of_two = i
else:
result[i] = result[i - power_of_two] + 1

return result

4 changes: 4 additions & 0 deletions 0338.Counting-Bits/step2_naive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
class Solution:
def countBits(self, n: int) -> list[int]:
return [i.bit_count() for i in range(n + 1)]

12 changes: 12 additions & 0 deletions 0338.Counting-Bits/step2_unset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Solution:
def countBits(self, n: int) -> list[int]:
if n == 0:
return [0]

result = [0] * (n + 1)

for i in range(1, n + 1):
result[i] = result[i & (i - 1)] + 1

return result

12 changes: 12 additions & 0 deletions 0338.Counting-Bits/step2_unsetv2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Solution:
def countBits(self, n: int) -> list[int]:
if n == 0:
return [0]

result = [0] * (n + 1)

for i in range(1, n + 1):
result[i] = result[i - (i & -i)] + 1

return result