LeetCode Remove Element

LeetCode解题之Remove Element


原题

删除一个数组中某一特定数值的元素。返回删除后的数组长度。

注意点:

  • 操作结束后的数字排列顺序不须要与之前同样
  • 超出返回长度的部分不须要处理

样例:

输入: nums [1, 2, 3, 4, 3, 2, 1],val = 1
输出: 5

解题思路

左右两个指针向中间靠拢,左指针找到一个等于val的值,右指针找到第一个不等于val的值。把右指针指向的值赋值给左指针。继续向中间靠拢。

AC源代码

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        left = 0
        right = len(nums) - 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 right + 1


if __name__ == "__main__":
    assert Solution().removeElement([1, 2, 3, 4, 3, 2, 1], 1) == 5
    assert Solution().removeElement([2], 3) == 1

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。

原文地址:https://www.cnblogs.com/mfmdaoyou/p/7010310.html