LeetCode 27. Remove Element

题目

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.

分析

  • 输入:一个数组和一个目标值
  • 任务:去掉数组中和目标值相等的元素
  • 条件:不申请新数组,对原数组原地操作,常数内存
  • 输出:新数组的长度

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
new_tail = 0
for i in range(len(nums)):
if nums[i] != val:
nums[new_tail] = nums[i]
new_tail = new_tail + 1
return new_tail

解释

其实和 26. Remove Duplicates from Sorted Array 是类似的,只不过每次遍历时不再是和新数组的最后一个值比较,而是跟给定的目标值比较,更加简单