一、题目
#27
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.
二、解析
从list中删除值为val的元素,最终返回删除后list的长度L。
评价方法:以返回的长度L为准,看list中前L个元素中是否存在val元素,没有即可。至于L之后有没有,无所谓
三、代码
思路有三种。
1.遍历list,检查每个元素,是val就删除,最终返回整个list长度。这里要注意一个细节,就是Python在del()时,后面元素自动向前补。结果2/13
2.while循环找出list中值为val的下标,然后一个一个删除。这里用到index方法,肯定要比第一种方法慢。结果5/13
3.上面两种方法都使用了Python的特性:自动补齐和index。更常用的方法是两个指针,使用swap而不是删除,将值为val的元素往后放,最后返回前不重复元素的长度即可。这种方法在实现是遇到了些小问题,继续想想。
代码1
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ length = len(nums) i = 0 delCount = 0 while i + delCount < length: if nums[i] == val: del(nums[i]) delCount += 1 else: i += 1 return length - delCount
代码2
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ try: while(1): pos = nums.index(val) del(nums[pos]) except: pass return len(nums)
原文:http://www.cnblogs.com/breada/p/4909123.html