• leetcodePython【27】: Remove Element


    1 python list可以使用索引的特性,从后往前遍历。
    2 按照list的常规做法,从开头每次验证下一个节点是否与val相同,
    最后验证头结点。
    3使用python list.remove()函数,删除所有的val。

    class Solution:
        def removeElement(self, nums, val):
            """
            :type nums: List[int]
            :type val: int
            :rtype: int
            """
            # method 1
            
            end = len(nums)-1
            while end > -1:
                if nums[end] == val:
                    del nums[end]
                end = end - 1
            return len(nums)
            
            # method 2
            
            if len(nums) == 0:
                return 0
            start = 0
            while 1:
                #print(start,nums)
                if start == (len(nums)-1) or len(nums) == 0:
                    break
                if nums[start+1] == val:
                    del nums[start+1]
                else:
                    start = start + 1 
            if nums[0] == val:
                del nums[0]
            return len(nums)
        
            # method 3
            #nums = [3,3]
            flag = True
            while flag:
                if val in nums:
                    nums.remove(val)
                else:
                    flag = False
            return len(nums)
    

    第一种最快,64ms,O(n)
    第二种第三种差不多,70ms左右。第二种判断条件多,
    第三种remove每次删去的是第一个val值,所以相当于每次删除
    把数组遍历了一遍。0(kn)k是val的个数。

  • 相关阅读:
    JS数组方法汇总 array
    jQuery性能优化
    js禁止保存网页的一些代码
    XML LINQ简介
    一个滑动条的DIV+CSS+JS实例
    JS的正则表达式
    jQuery中$.ajax的实现
    MSSQL 2005删除所有表的语句[转]
    Jquery Toggle with Images
    SQLIte default date CURRENT_TIMESTAMP
  • 原文地址:https://www.cnblogs.com/Years4Nancy/p/8414799.html
Copyright © 2020-2023  润新知