class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if not nums:
return 0
i = 0
for j in range(len(nums)):
if nums[j] != val:
nums[i] = nums[j]
i += 1
return i
a = [1,1,2,1,3,1]
print Solution().removeElement(a, 1)
print a
问题
https://leetcode.com/problems/remove-element/description/
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.
思路
思路和 #42 比较相似,也是采用双指针的方法,一个指针去遍历nums,另外一个指针原地更新array
解答