Add Move Zeroes problem documentation#15
Conversation
| return | ||
| ``` | ||
| - in-placeはこういうremove and appendもだめで入れ替えのみ許容なのかコピーを作らなければいいのかわからない。 | ||
| - 0をinfとして扱うようにsort関数を書くのも思いつくところ->他の数字列は保存しないといけないことを忘れていた。 |
| non_zero_numbers += 1 | ||
| for i in range(non_zero_numbers, len(nums)): | ||
| nums[i] = 0 | ||
| return |
There was a problem hiding this comment.
読みやすいと思います。
一応、swapにしておく利点としては、numsがクラスのインスタンスの配列だったりして(0かどうかチェックする変数以外の)他の情報が入っているような場合に、それを再利用できるというのがあるかもしれません。
There was a problem hiding this comment.
あ、あとreturnは省略しても動く気がします。
ドキュメントに省略できるみたいな記述がちょっと見つけられなかったんですが、どちらにしてもNoneが返されると認識しています。(違ったらすみません)
https://docs.python.org/3/reference/simple_stmts.html#the-return-statement
There was a problem hiding this comment.
チュートリアルには書いてありました。
In fact, even functions without a return statement do return a value, albeit a rather boring one. This value is called None (it’s a built-in name).
https://docs.python.org/3/tutorial/controlflow.html#defining-functions
| def moveZeroes(self, nums: List[int]) -> None: | ||
| count_zeroes = 0 | ||
| while 0 in nums: | ||
| nums.remove(0) |
| return | ||
| ``` | ||
|
|
||
| - ネストが深いことと二重ループとswapの繰り返しで遅いことが気になる。 |
There was a problem hiding this comment.
if nums[i] != 0:
continue
for j in range(i, len(nums)):等のようにするとネストは浅くできると思います。
| ```python | ||
| class Solution: | ||
| def moveZeroes(self, nums: List[int]) -> None: | ||
| non_zero_numbers = 0 |
There was a problem hiding this comment.
non_zero_numbers という名前からは、ゼロでない数字のリストまたは集合というニュアンスが感じあられます。自分なら num_non_zeros と名付けると思います。
This problem:
https://leetcode.com/problems/move-zeroes/
Next problem:
https://leetcode.com/problems/k-th-symbol-in-grammar/