Leetcode P27 Remove Element @python Lang (LL)

9 篇文章 0 订阅
9 篇文章 0 订阅

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

Content:
在这里插入图片描述
Attention:

  1. return length
  2. first n elements, no matter what leave beyond elements
  3. the order can be arbitrary

Method 1: Two pointers
Algorithm: same with P26

  1. one pointer cur record the position of array
  2. second pointer i traverse the whole array

Code:

class Solution:
    def removeElement(self,nums,val):
        cur = 0        
        for i in range(len(nums)):
            if nums[i] != val:               
                nums[cur] = nums[i]
                cur += 1
        return cur

Time complexity:
O(n): if n elements in array, both cur and i traverse 2n at most.

Method 2: Counter (record the number of val)
same with P26
Code:

class Solution:
    def removeElement(self,nums,val):
        count = 0        
        for i in range(len(nums)):
            if nums[i] == val:               
                count += 1
            else:
            	nums[i-count] = nums[i]
        return len(nums)-count

Method 3: last fill (in the use of the order can be arbitrary)
Algorithm:

  1. n means the length of nums
  2. i traverse the whole array, condition (i<n)
  3. if nums[i] == val, nums[i] = the last number of array, decrease n at the same time, if not, i++
  4. return n

Code:

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

Best situation:
In this approach, the number of assignment operations is equal to the number of elements to remove. So it is more efficient if elements to remove are rare.

Time complexity:
O(n), both i and n traverse at most n times.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值