From bdb0d45864bae3ef3988e0a01b2ab5283447eff4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A7=A6=E8=8B=B1=E6=9D=B0?= <327782001@qq.com> Date: Thu, 22 Jun 2023 09:24:08 +0800 Subject: [PATCH] =?UTF-8?q?fix:=E7=A7=BB=E9=99=A4=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../problem_solving_03.py" | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git "a/14_\345\210\267\351\242\230/problem_solving_03.py" "b/14_\345\210\267\351\242\230/problem_solving_03.py" index 5dc2b12..2445a9c 100644 --- "a/14_\345\210\267\351\242\230/problem_solving_03.py" +++ "b/14_\345\210\267\351\242\230/problem_solving_03.py" @@ -6,6 +6,12 @@ from typing import List class Solution: def removeElement(self, nums: List[int], val: int) -> int: + """ + 左指针 单指针遍历 + :param nums: + :param val: + :return: + """ left = 0 for index in range(0, len(nums)): if nums[index] != val: @@ -13,7 +19,24 @@ class Solution: left += 1 return left + def removeElement2(self, nums: List[int], val: int) -> int: + """ + 双指针优化,左右夹逼 + :param nums: + :param val: + :return: + """ + left = 0 + right = len(nums) + while left < right: + if nums[left] == val: + nums[left] = nums[right - 1] + right -= 1 + else: + left += 1 + return left + if __name__ == '__main__': - result = Solution().removeElement([2], 3) + result = Solution().removeElement2([2], 3) print(result) -- GitLab