Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions 283. Move Zeroes/283. Move Zeroes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# 283. Move Zeroes
## STEP1
- 何も見ずに解いてみる
- 前から順に見ていき、入れ替えるべき index を見つけて交換する。
- [1, 0] のようなケースを見落としていた。non_zero_index は zero_index より大きくなくてはいけない。
```python
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zero_index = 0
non_zero_index = 0
while True:
while zero_index < len(nums) and nums[zero_index] != 0:
zero_index += 1
non_zero_index = max(non_zero_index, zero_index + 1)
while non_zero_index < len(nums) and nums[non_zero_index] == 0:
non_zero_index += 1
if non_zero_index >= len(nums) or zero_index >= len(nums):
break

nums[non_zero_index], nums[zero_index] = nums[zero_index], nums[non_zero_index]
non_zero_index += 1
zero_index += 1
```

## STEP2
### プルリクやドキュメントを参照
- https://github.com/olsen-blue/Arai60/pull/55/files
- for 文一つで書けることは気が付かなかった。確かに、前から見るだけで 0 でない要素を詰めるべき位置はわかる。
- 非ゼロの時に処理が起こる、かつ短い処理でので、if num == 0:continue と書く必要はないと感じた。
```python
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
num_non_zero_items = 0
for i, num in enumerate(nums):
if num != 0:
nums[num_non_zero_items], nums[i] = nums[i], nums[num_non_zero_items]
num_non_zero_items += 1
```

- https://github.com/shining-ai/leetcode/pull/54/files#diff-326ca2ce90ef5e7bf7e21c2676a184474a21c4d3d213d13c81e3fc5675c23267R4-R16
- ほとんど同じですが、0 をまとめて書くことでわかりやすくなるかもしれない。わざわざ分ける必要性は微妙なところ。
```python
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
num_non_zero_items = 0
for i, num in enumerate(nums):
if num != 0:
nums[num_non_zero_items] = nums[i]
num_non_zero_items += 1
for i in range(num_non_zero_items, len(nums)):
nums[i] = 0
```
## STEP3
### 3回ミスなく書く
- あとで nums[i] を使うため、enumerate を使うことで得られるわかりやすさを享受できていないと思ったため、単に range を使うことにした。
```python
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
num_non_zero_items = 0
for i in range(len(nums)):
if nums[i] != 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.

if nums[i] == 0:
continue
のほうが私は好きです。

nums[num_non_zero_items], nums[i] = nums[i], nums[num_non_zero_items]
num_non_zero_items += 1
```

1分,1分,1分で3回Accept