LeetCode专题-Python实现之第27题:Remove Element

时间:2023-03-08 22:55:43
LeetCode专题-Python实现之第27题:Remove Element

导航页-LeetCode专题-Python实现

相关代码已经上传到github:https://github.com/exploitht/leetcode-python

文中代码为了不动官网提供的初始几行代码内容,有一些不规范的地方,比如函数名大小写问题等等;更合理的代码实现参考我的github repo

1、读题

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.

给定一个数组和一个值,移除这个数组中的所有该值。不要申请额外空间,在当前数组操作,操作完成后超出需要长度的值是什么无所谓。也就是说,数组[3,2,2,3]给定值为3,则处理之后需要返回2,数组处理成[2,2,…],前2个对就行了,后面的无所谓。这道题其实和上一题思路是一样的,都是原地处理数组,返回length,超出length的内容不关注。

2、解题

同上一题,只需要维护2个指针就OK了,快指针遍历数组,发现val直接后移,若不是则赋值给慢指针。代码很短,如下:

class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
point = 0
for i in range(0, len(nums)):
if nums[i] != val:
nums[point] = nums[i]
point += 1
return point