【python3】leetcode 27. Remove Element(easy)

120 篇文章 0 订阅

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

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值