-
Notifications
You must be signed in to change notification settings - Fork 0
283. Move Zeroes #20
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
283. Move Zeroes #20
Conversation
|
|
||
| for i in range(non_zero_pos, len(nums)): | ||
| nums[i] = 0 | ||
| ``` |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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なんだ…) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
list の末尾以外の要素に対して pop() を呼び出すと、それより後の要素を手前にずらさなければならないため、時間計算量 O(n) がかかり、重くなります。原則避けることをおすすめします。
283. Move Zeroes
次回予告: 349. Intersection of Two Arrays