From a30d23871841797548b87ab1cc09ceda7be19bca Mon Sep 17 00:00:00 2001 From: leeeeeeewii <54872662+leeeeeeewii@users.noreply.github.com> Date: Wed, 12 Jan 2022 00:29:24 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00283.=E7=A7=BB=E5=8A=A8?= =?UTF-8?q?=E9=9B=B6=20python=E4=B8=8D=E5=90=8C=E6=96=B9=E6=B3=95=EF=BC=8C?= =?UTF-8?q?Go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0283.移动零.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0283.移动零.md b/problems/0283.移动零.md index 13b9c26c..bb75a696 100644 --- a/problems/0283.移动零.md +++ b/problems/0283.移动零.md @@ -89,9 +89,33 @@ Python: for i in range(slow, len(nums)): nums[i] = 0 ``` +交换前后变量,避免补零 +```python + def moveZeroes(self, nums: List[int]) -> None: + slow, fast = 0, 0 + while fast < len(nums): + if nums[fast] != 0: + nums[slow], nums[fast] = nums[fast], nums[slow] + slow += 1 # 保持[0, slow)区间是没有0的 + fast += 1 +``` Go: +```go +func moveZeroes(nums []int) { + slow := 0 + for fast := 0; fast < len(nums); fast ++ { + if nums[fast] != 0 { + temp := nums[slow] + nums[slow] = nums[fast] + nums[fast] = temp + slow++ + } + } +} +``` + JavaScript: ```javascript var moveZeroes = function(nums) {