Skip to content

283, Move Zeroes#18

Open
nittoco wants to merge 1 commit intomainfrom
nittoco-patch-18
Open

283, Move Zeroes#18
nittoco wants to merge 1 commit intomainfrom
nittoco-patch-18

Conversation

@nittoco
Copy link
Copy Markdown
Owner

@nittoco nittoco commented Jun 11, 2024

URL: https://leetcode.com/problems/move-zeroes/
問題文: Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

URL: https://leetcode.com/problems/move-zeroes/
問題文: Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

```python

class Solution:
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 埋めをするのであれば、この解法が一番スマートだと思います。

"""
Do not return anything, modify nums in-place instead.
"""
nonzero_count = 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.

自分なら num_non_zeros と名付けると思います。

@@ -0,0 +1,118 @@
## Step1

- 最初にパッと思いついたやつ、時間計算量O(len(nums)^2)なので、ギリギリ
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

この問題を読んだとき、一番初めに思い付いたのは C++ の標準ライブラリの std::remove() でした。
https://cpprefjp.github.io/reference/algorithm/remove.html

for i in range(len(nums)):
if nums[i]:
nonzero_index = i
while nonzero_index-1 >= 0 and nums[nonzero_index - 1] == 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.

@rihib rihib mentioned this pull request Dec 17, 2024
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.

2 participants