27. Remove Element [easy] (Python)

题目链接

https://leetcode.com/problems/remove-element/

题目原文

Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example:
Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

题目翻译

给定一个数组和一个值,直接在该数组中删除所有该值,并返回新的数组长度。元素顺序可以改变,数组在新长度之后的元素无所谓。
比如:给定数组nums = [3, 2, 2, 3],值val = 3,你的函数应该返回长度2,并且数组nums的前两个元素是2。

思路方法

思路一

用两个指针,一个指针顺序扫描所有元素判断当前元素是否是要删除的,另一个指针一直指向下一个不是要删除元素的位置。这样相当于把原数组中要删除的数去除后,所有其他数字前移。

代码

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        length = 0
        for i in xrange(len(nums)):
            if nums[i] != val:
                nums[length] = nums[i]
                length += 1
        return length

思路二

这个思路比较麻烦,先扫描一遍将所有要删除的数找到并记录位置。再扫描一遍把这些位置用列表后面的数字填充。

代码

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        rm_index = []
        for i in xrange(len(nums)):
            if nums[i] == val:
                rm_index.append(i)
        last = len(nums) - 1
        for i in rm_index:
            while last >= 0 and nums[last] == val:
                last -= 1
            if last < 0:
                break
            nums[i] = nums[last]
            last -= 1
        return len(nums) - len(rm_index)

思路三

在思路二的基础上进一步考虑,其实不需要扫描两遍。扫描到要删除的数时,直接拿数组最末的数字填充,然后继续从这个填充位置向后扫描即可。

代码

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        length, i = len(nums), 0 
        while i < length:
            if nums[i] == val:
                nums[i] = nums[length - 1]
                length -= 1
            else:
                i += 1
        return length

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51578854

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值