• 欢迎来到莫知我哀的博客,日常不定时更新C++、C#、Unity、OpenGL、游戏开发相关文章。同步博客: CSDN
  • 网站左下角可以开启好听的背景音乐~~
  • 如果您觉得本博客很有看点,那么赶紧使用Ctrl+D 收藏吧

[LeetCode] 27. Remove Element

算法练习 wahh 461次浏览 0个评论 扫描二维码

题目

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.

Example 1:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned 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 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]);
}

 

原题链接:https://leetcode.com/problems/remove-element/description/

 

题意

输入一个数组和一个额外的值val,从数组中删除所有值为val的元素,输出剩余数组的长度,并将剩余元素按照原本数组的顺序放置在数组的首部。要求:额外的空间复杂度为O(1)。

 

分析

和26题目类似,定义x为剩余数组长度,线性遍历数组,每当找到一个不为val的元素就放置到x位置,并将x++。

 

代码

 


莫知我哀 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:[LeetCode] 27. Remove Element
喜欢 (1)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
Title - Artist
0:00