概述
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.
双指针法
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 27. Remove element所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复