diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index dbde3d19..2a2005d7 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -253,6 +253,27 @@ class Solution: ``` +``` python 3 +# 相向双指针法 +# 时间复杂度 O(n) +# 空间复杂度 O(1) +class Solution: + def removeElement(self, nums: List[int], val: int) -> int: + n = len(nums) + left, right = 0, n - 1 + while left <= right: + while left <= right and nums[left] != val: + left += 1 + while left <= right and nums[right] == val: + right -= 1 + if left < right: + nums[left] = nums[right] + left += 1 + right -= 1 + return left + +``` + ### Go: ```go