我是靠谱客的博主 紧张云朵,这篇文章主要介绍leetcode 27. Remove element,现在分享给大家,希望可以做个参考。

Remove element

Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}

在这里插入图片描述

重点:不分配附加的空间给另外一个array,需要通过modifying the input array in-place with O(1) extra memory.

双指针法

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution: def removeElement(self, nums: List[int], val: int) -> int: l,r=0,len(nums)-1 if len(nums)==0: return 0 while l<r: while (l<r and nums[l]!=val): l+=1 while (l<r and nums[r]==val): r-=1 nums[l],nums[r]=nums[r],nums[l] return l if nums[l]==val else l+1

记录
(1)双指针法,设定两个指针,一个从左往右移动,如果遇到第一个val,就停止,另外一个指针从右开始往左移动,遇到第一个不是val的就停止。然后两个元素交换。
(2)移动到两个指针到一起后停止。

我犯的错误
(1)while的条件确定,在里面的while也需要有l<r这项,我把这项弄错了,所以结果一直不对。如果没有这个,也许会导致l>r,就出错了。
(2)细节部分,比如r的初始值是len(nums)-1而不是len(nums)

最后

以上就是紧张云朵最近收集整理的关于leetcode 27. Remove element的全部内容,更多相关leetcode内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(51)

评论列表共有 0 条评论

立即
投稿
返回
顶部