【Leetcode】【python】Remove Element

来源:互联网 发布:韩语入门教材知乎 编辑:程序博客网 时间:2024/06/05 03:13

题目大意

去掉数组中等于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

总结

原创粉丝点击