From d1e96301933881b0b7e7e14a6aeab804a32a9a64 Mon Sep 17 00:00:00 2001 From: Wen Date: Thu, 26 Aug 2021 13:20:47 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=200027.=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E5=85=83=E7=B4=A0.md=20Python3=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0027.移除元素.md | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index fadd4d7e..6fce4c6e 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -144,15 +144,28 @@ class Solution { Python: -```python +```python3 class Solution: - def removeElement(self, nums: List[int], val: int) -> int: - i,n = 0,len(nums) - for j in range(n): - if nums[j] != val: - nums[i] = nums[j] - i += 1 - return i + """双指针法 + 时间复杂度:O(n) + 空间复杂度:O(1) + """ + + @classmethod + def removeElement(cls, nums: List[int], val: int) -> int: + fast = slow = 0 + + while fast < len(nums): + + if nums[fast] != val: + nums[slow] = nums[fast] + slow += 1 + + # 当 fast 指针遇到要删除的元素时停止赋值 + # slow 指针停止移动, fast 指针继续前进 + fast += 1 + + return slow ```