Skip to content
Merged
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
57 changes: 57 additions & 0 deletions 競技プロ就活部PR用/283. Move Zeroes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
近くで似た問題を解いていたため、かなり早く解けた。
## Two-pointersによる解法 ★
---
### 1回目 (2m36s)
時間計算量: O(N)
空間計算量: O(1)

```python
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
left = 0

for right in range(len(nums)):
if nums[right] != 0:
nums[left], nums[right] = nums[right], nums[left]
left += 1
```


left, right -> left_most_zero, iに変更

### 2回目
```python
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
left_most_zero = 0

for i in range(len(nums)):
if nums[i] != 0:
nums[left_most_zero], nums[i] = nums[i], nums[left_most_zero]
left_most_zero += 1
```

## 0以外を左端に詰めていく解法
```python
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zero_index = 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.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

liquo-riceさん、ありがとうございます。
zero_indexにしてしまうと、客観的に(or 後から自分で見た場合)自然言語の直感と反するんですね。
今まであまり意識できていなかったので、覚えておきます。SuperHotDogCatさんにもご指摘いただいたように、non_zero_length, が良い塩梅でしょうかね。


for i in range(len(nums)):
if nums[i] == 0:
continue
nums[zero_index] = nums[i]
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

zero_indexだとzeroが入っているindexなのかなと思ってしまいます。多分上のコードを見る感じだとnon_zero_lengthぐらいでしょうか

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。なるほどです。

zero_index += 1

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