fix:移除元素

上级 cbdb8c91
...@@ -6,6 +6,12 @@ from typing import List ...@@ -6,6 +6,12 @@ from typing import List
class Solution: class Solution:
def removeElement(self, nums: List[int], val: int) -> int: def removeElement(self, nums: List[int], val: int) -> int:
"""
左指针 单指针遍历
:param nums:
:param val:
:return:
"""
left = 0 left = 0
for index in range(0, len(nums)): for index in range(0, len(nums)):
if nums[index] != val: if nums[index] != val:
...@@ -13,7 +19,24 @@ class Solution: ...@@ -13,7 +19,24 @@ class Solution:
left += 1 left += 1
return left 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__': if __name__ == '__main__':
result = Solution().removeElement([2], 3) result = Solution().removeElement2([2], 3)
print(result) print(result)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册