标签:
题目:
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.
链接: http://leetcode.com/problems/remove-element/
一刷,做不到一遍bug free。19行比较有意思,因为left, right相对位置判断在值判断之前,当两个下标重合时,至少有一个是不符合第二个条件的,所以要判断当前值是否等于val
1 class Solution(object): 2 def removeElement(self, nums, val): 3 """ 4 :type nums: List[int] 5 :type val: int 6 :rtype: int 7 """ 8 if not nums: 9 return 0 10 left = 0 11 right = len(nums) - 1 12 length = len(nums) 13 14 while left <= right: 15 while left < right and nums[left] != val: 16 left += 1 17 while right > left and nums[right] == val: 18 right -= 1 19 if left == right: 20 return left + 1 if nums[left] != val else left 21 nums[left] = nums[right] 22 left += 1 23 right -= 1 24 return left
标签:
原文地址:http://www.cnblogs.com/panini/p/5573362.html