From 2e4c2cc72b81ac2268f3c4211833506e083ebaff Mon Sep 17 00:00:00 2001 From: Hiro Funatsuka Date: Sat, 2 May 2026 00:06:09 +0900 Subject: [PATCH] Solve move zeroes --- 283_move_zeroes/.DS_Store | Bin 0 -> 6148 bytes 283_move_zeroes/problem.md | 1 + 283_move_zeroes/step1.md | 29 +++++++++++++++++++++ 283_move_zeroes/step2.md | 50 +++++++++++++++++++++++++++++++++++++ 283_move_zeroes/step3.md | 19 ++++++++++++++ 5 files changed, 99 insertions(+) create mode 100644 283_move_zeroes/.DS_Store create mode 100644 283_move_zeroes/problem.md create mode 100644 283_move_zeroes/step1.md create mode 100644 283_move_zeroes/step2.md create mode 100644 283_move_zeroes/step3.md diff --git a/283_move_zeroes/.DS_Store b/283_move_zeroes/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5008ddfcf53c02e82d7eee2e57c38e5672ef89f6 GIT binary patch literal 6148 zcmeH~Jr2S!425mzP>H1@V-^m;4Wg<&0T*E43hX&L&p$$qDprKhvt+--jT7}7np#A3 zem<@ulZcFPQ@L2!n>{z**++&mCkOWA81W14cNZlEfg7;MkzE(HCqgga^y>{tEnwC%0;vJ&^%eQ zLs35+`xjp>T0 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秒