【python3】leetcode 27. Remove Element(easy)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maotianyi941005/article/details/84963624

27. Remove Element(easy)

Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.

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

Example 1:

Given nums = [3,2,2,3], val = 3,

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

It doesn't matter what you leave beyond the returned length.

 注意虽然需要的返回值是int,但是同时会测评你的nums是否去掉了所有val,且是inplace修改,即引用地址没变

还有一点是val值可能不存在nums中,需要提前判断

1 我的最优解

思路:因为题目一直提醒说剩下的nums可以不必按顺序,所以机智如我,先排序一波,此时val的位置index和数量count是已知的

利用切片把从[index :index+count]的val 都赋值为空[]

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

        if not val in nums: return len(nums)
        num = len(nums) - nums.count(val)
        nums.sort()
        nums[nums.index(val):nums.index(val)+nums.count(val)] = []
        return num

Runtime: 36 ms, faster than 99.77% of Python3  

 2 普通思路

计算有几个val,就删几次val

class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        if not val in nums: return len(nums)
        num = len(nums) - nums.count(val)
        length = nums.count(val)
        for i in range(length):
            nums.remove(val)
        
        return num

猜你喜欢

转载自blog.csdn.net/maotianyi941005/article/details/84963624