Skip to content

Conversation

@skypenguins
Copy link
Owner

@skypenguins skypenguins commented Aug 24, 2025

283. Move Zeroes

次回予告: 349. Intersection of Two Arrays

@skypenguins skypenguins self-assigned this Aug 24, 2025

for i in range(non_zero_pos, len(nums)):
nums[i] = 0
```

Choose a reason for hiding this comment

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

良いと思います。

```py
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
non_zero_pos = 0

Choose a reason for hiding this comment

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

pos よりも index の方が馴染みがあるようには思いますが、好みの範囲かと思います。

* https://github.com/fhiyo/leetcode/pull/54
- Python
- `nonzeros` に非ゼロな値をコピーして退避し、それを`nums` に追加していく方法
- (コピー作成してもOKなんだ…)

Choose a reason for hiding this comment

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

これはコピーしても ok というか、補助的なリスト (nonzeros) を用意して、最終的には nums を mutate していますね。コピーしたリストを返しているわけではないので、念のためコメントさせてください。

nums_len = len(nums)
for _ in range(nums_len):
if nums[nums_i] == 0:
nums.pop(nums_i)
Copy link

Choose a reason for hiding this comment

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

list の末尾以外の要素に対して pop() を呼び出すと、それより後の要素を手前にずらさなければならないため、時間計算量 O(n) がかかり、重くなります。原則避けることをおすすめします。

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants