Skip to content

Add Move Zeroes problem documentation#15

Open
yakataN wants to merge 1 commit into
mainfrom
Move-Zeroes-1
Open

Add Move Zeroes problem documentation#15
yakataN wants to merge 1 commit into
mainfrom
Move-Zeroes-1

Conversation

@yakataN
Copy link
Copy Markdown
Owner

@yakataN yakataN commented Sep 20, 2025

return
```
- in-placeはこういうremove and appendもだめで入れ替えのみ許容なのかコピーを作らなければいいのかわからない。
- 0をinfとして扱うようにsort関数を書くのも思いつくところ->他の数字列は保存しないといけないことを忘れていた。
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0以外を全部同じ数字(たとえば0とか)として扱うようにすればできそうです。

non_zero_numbers += 1
for i in range(non_zero_numbers, len(nums)):
nums[i] = 0
return
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

読みやすいと思います。
一応、swapにしておく利点としては、numsがクラスのインスタンスの配列だったりして(0かどうかチェックする変数以外の)他の情報が入っているような場合に、それを再利用できるというのがあるかもしれません。

Copy link
Copy Markdown

@potrue potrue Sep 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

あ、あとreturnは省略しても動く気がします。
ドキュメントに省略できるみたいな記述がちょっと見つけられなかったんですが、どちらにしてもNoneが返されると認識しています。(違ったらすみません)
https://docs.python.org/3/reference/simple_stmts.html#the-return-statement

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

チュートリアルには書いてありました。

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)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

最悪計算量 O(n^2) になってそうです。

return
```

- ネストが深いことと二重ループとswapの繰り返しで遅いことが気になる。
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

non_zero_numbers という名前からは、ゼロでない数字のリストまたは集合というニュアンスが感じあられます。自分なら num_non_zeros と名付けると思います。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants