[Leetcode][python]Remove Element/移除元素

题目大意

去掉数组中等于elem的元素,返回新的数组长度,数组中的元素不必保持原来的顺序。

解题思路

双指针
使用头尾指针,头指针碰到elem时,与尾指针指向的元素交换,将elem都换到数组的末尾去。

代码

判断与指定目标相同

class Solution(object):
    def removeElement(self, nums, val):
        """ :type nums: List[int] :type val: int :rtype: int """
        front = len(nums)-1
        behind = len(nums)-1
        number = 0
        while front >= 0:
            print 'now:', front, behind
            if nums[front] == val:
                print front, behind
                number += 1
                nums[front], nums[behind] = nums[behind], nums[front]
                behind -= 1
            front -= 1
        print number
        return len(nums) - number

判断与指定目标不同

class Solution(object):
    def removeElement(self, nums, val):
        """ :type nums: List[int] :type val: int :rtype: int """

        size = 0
        length = len(nums)

        for i in range(length):
            if nums[i] != val:

                nums[size] = nums[i]
                size += 1
        return size

总结

全部评论

相关推荐

05-12 17:00
门头沟学院 Java
king122:你的项目描述至少要分点呀,要实习的话,你的描述可以使用什么技术,实现了什么难点,达成了哪些数字指标,这个数字指标尽量是真实的,这样面试应该会多很多,就这样自己包装一下,包装不好可以找我,我有几个大厂最近做过的实习项目也可以包装一下
点赞 评论 收藏
分享
重生我想学测开:嵌入式的问题,我准备入行京东外卖了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务