diff --git a/283_move_zeroes/.DS_Store b/283_move_zeroes/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/283_move_zeroes/.DS_Store differ diff --git a/283_move_zeroes/problem.md b/283_move_zeroes/problem.md new file mode 100644 index 0000000..4d37c3a --- /dev/null +++ b/283_move_zeroes/problem.md @@ -0,0 +1 @@ +## 問題: [283. Move Zeroes](https://leetcode.com/problems/move-zeroes/description/) diff --git a/283_move_zeroes/step1.md b/283_move_zeroes/step1.md new file mode 100644 index 0000000..f8ea5a5 --- /dev/null +++ b/283_move_zeroes/step1.md @@ -0,0 +1,29 @@ +# Step 1 + +- 0を探すポインタと0以外を探すポインタを使う +- 0に遭遇したら、そのインデックスの1つ先から0以外を探す +- 0以外を見つけたら、その値と前述で見つけた0を入れ替える + +```python +class Solution: + def moveZeroes(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + l, r = 0, 1 + while l < len(nums) and r < len(nums): + if nums[l] != 0: + l += 1 + continue + r = l + 1 + while r < len(nums): + if nums[r] == 0: + r += 1 + else: + nums[l], nums[r] = nums[r], nums[l] + break +``` + +時間計算量: O(n^2) + +空間計算量: O(1) diff --git a/283_move_zeroes/step2.md b/283_move_zeroes/step2.md new file mode 100644 index 0000000..0f81525 --- /dev/null +++ b/283_move_zeroes/step2.md @@ -0,0 +1,50 @@ +# Step 2 + +- Step 1のコードは遅い +- rのインデックスを毎回lの1個先にリセットしないようにしたい + +```python +class Solution: + def moveZeroes(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + l, r = 0, 0 + while l < len(nums) and r < len(nums): + if nums[l] != 0: + l += 1 + r = max(r, l) + continue + while r < len(nums): + if nums[r] == 0: + r += 1 + else: + nums[l], nums[r] = nums[r], nums[l] + break + +``` + +時間計算量: $O(n)$ + +空間計算量: $O(1)$ + +- 他の人のコード見たらもっとスマートなのがあった +- 0でない値が次にどのインデックスに来るか変数で持つ +- 変数は0で始まり、0でない値がみつかったら、変数が示すインデックスに格納されている値と入れ替える + +```python +class Solution: + def moveZeroes(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + non_zero_index = 0 + for i in range(len(nums)): + if nums[i] != 0: + nums[i], nums[non_zero_index] = nums[non_zero_index], nums[i] + zero_index += 1 + +``` +時間計算量: $O(n)$ + +空間計算量: $O(1)$ \ No newline at end of file diff --git a/283_move_zeroes/step3.md b/283_move_zeroes/step3.md new file mode 100644 index 0000000..1fe7c86 --- /dev/null +++ b/283_move_zeroes/step3.md @@ -0,0 +1,19 @@ +# Step 3 + +```python +class Solution: + def moveZeroes(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + non_zero_index = 0 + for i in range(len(nums)): + if nums[i] != 0: + nums[i], nums[non_zero_index] = nums[non_zero_index], nums[i] + zero_index += 1 +``` +1回目: 1分 9秒 + +2回目: 1分 2秒 + +3回目: 0分 56秒