标签:
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn‘t matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3]
, val = 3
Your function should return length = 2, with the first two elements of nums being 2.
这题要求从已知数组中查找某个元素,要求in place 删除该元素,并返回新序列的长度,题目提示新长度之后的数组中的内容不用考虑。
数组要求in place删除元素,很容易想起来从最右端开始删除。具体在这题的思路是维护双指针,指针p1从头开始移动,指针p2从尾开始移动。
if not nums: return 0 p1 = 0 p2 = len(nums)-1 ret = 0 while p1<=p2: if nums[p1]!=val: p1 += 1 else: nums[p1]=nums[p2] p2 -=1 return p2+1
标签:
原文地址:http://www.cnblogs.com/sherylwang/p/5438250.html