[删除元素]Remove Element

一、题目

#27

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

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

 

二、解析

从list中删除值为val的元素,最终返回删除后list的长度L。

评价方法:以返回的长度L为准,看list中前L个元素中是否存在val元素,没有即可。至于L之后有没有,无所谓

 

三、代码

思路有三种。

1.遍历list,检查每个元素,是val就删除,最终返回整个list长度。这里要注意一个细节,就是Python在del()时,后面元素自动向前补。结果2/13

2.while循环找出list中值为val的下标,然后一个一个删除。这里用到index方法,肯定要比第一种方法慢。结果5/13

3.上面两种方法都使用了Python的特性:自动补齐和index。更常用的方法是两个指针,使用swap而不是删除,将值为val的元素往后放,最后返回前不重复元素的长度即可。这种方法在实现是遇到了些小问题,继续想想。

 

代码1

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

 

代码2

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        try:
            while(1):
                pos = nums.index(val)
                del(nums[pos])
        except:
            pass
        return len(nums)
            

 --------------------------

有意思,刚实现了代码3,速度却不是最快的。5/13

class Solution(object):
    

    
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        if len(nums) == 0:
            return 0
        elif len(nums) == 1:
            if nums[0] == val:
                del(nums[0])
                return 0
            else:
                return 1
        elif len(nums) == 2:
            if nums[0] == nums[1]:
                if nums[0] == val:
                    return 0
                else:
                    return 2
            else:
                if nums[0] == val:
                    del(nums[0])
                    return 1
                elif nums[1] == val:
                    del(nums[1])
                    return 1
        
        i  = 0
        j = len(nums) - 1
        count = 0
        while i <= j:
            while nums[j] == val and j >= 0: 
                j -= 1
                count += 1
            if nums[i] == val and i <= j:
                temp = nums[i]
                nums[i] = nums[j]
                nums[j] = temp
                i += 1
                j -= 1
                count += 1
            else:
                i += 1
        return len(nums) - count

思路:让i之前没有val的元素,j之后全部为值是val元素。做法如下:

1.若i为val,j不为val,就交换。这样做有个前提,即j不能为val,所以就从尾向前遍历,停在不为val的地方。之间遇到几个val就count+1

2.交换后,i向后,j向前,发现了一个val,所以count+1

3.其他情况,i不为val,则i向后,i+1

最终,count就是发现了几个val。有意思的是,并不是最快的。问题出在哪里呢?

posted @ 2015-10-25 17:33  面包包包包包包  阅读(426)  评论(0编辑  收藏  举报