zoukankan      html  css  js  c++  java
  • 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) 来获得相关源代码。

  • 相关阅读:
    async 和 await
    C#中lock死锁
    Attribute特性
    数据库优化
    EF(ORM)
    依赖注入
    面向接口编程
    EF乐观锁与悲观锁
    为什么要使用RESTFUL风格?
    cloudsim 3.0.3下载与安装教程
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/7010310.html
Copyright © 2011-2022 走看看