zoukankan      html  css  js  c++  java
  • LeetCode#27 Remove Element

    Problem Definition:

    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.

    Solution:

    1)一种最简单的思想,花一点空间。

    1 def removeElement(nums, val):
    2         nu=[]
    3         for n in nums:
    4             if n!=val:
    5                 nu+=n,
    6         nums[:]=nu[:]
    7         return len(nums)

    2)两头扫描,替换。

     1 def removeElement(nums, val):
     2         p,q=0,len(nums)-1
     3         while p<=q:
     4             if nums[p]!=val:
     5                 p+=1
     6             elif nums[q]==val:
     7                 q-=1
     8             else:
     9                 nums[p],nums[q]=nums[q],nums[p]
    10                 p+=1
    11                 q-=1
    12         nums[:]=nums[:q+1]
    13         return len(nums)

    3)计数 1。

    1 def removeElement(nums, val):
    2         m=0    #计应保留的元素数
    3         for e in nums:
    4             if e!=val:
    5                 nums[m]=e
    6                 m+=1
    7         nums[:]=nums[:m]
    8         return m

    4)计数 2。

     1 def removeElement(nums, val):
     2         m=0    #计应删除的元素数
     3         for i,e in enumerate(nums):
     4             if e==val:
     5                 m+=1
     6             else:
     7                 nums[i-m]=e
     8         ol=len(nums)
     9         nums[:]=nums[:ol-m]
    10         return len(nums)
  • 相关阅读:
    8月4日
    8月3日 hive配置
    8月2日
    8月1日
    7月31日
    7月30日
    7月29日
    7月28日
    第六周总结
    重大技术需求进度报告一
  • 原文地址:https://www.cnblogs.com/acetseng/p/4674691.html
Copyright © 2011-2022 走看看