Given an array nums and a value val, remove all instances of that value in-place and return the new length.
给定一个数组num和一个值,在这个数组中删除这个值得全部实例并且返回新的长度
Donot allocate extra space for another array, you must do this by modifying the input arrayin-place with O(1) extra memory.
不要为其他的数组分配额外的空间,你必须修改输入的数组,用O(1)的空间
The orderof elements can be changed. It doesn't matter what you leave beyond the new length.
元素的顺序可以改变,你的新长度并不重要。
Example 1:
例子1
Given nums = [3,2,2,3], val = 3,
给你一个数组和val
Your function should return length = 2, with the first two elements of nums being 2.
你的函数应该能够返回length=2,同时nums中前两个元素为2。
It doesn't matter what you leave beyond the returned length.
你返回长度之后是什么并不重要。
Example 2:
例子2
Given nums = [0,1,2,2,3,0,4,2], val = 2,
给你一个数组nums和val
Your functionshouldreturnlength = 5, withthefirstfiveelementsofnumscontaining 0, 1, 3, 0, and 4.
你的函数能够返回length=5,同时nums中前5个元素应该包含0,1,3,0,4。
Notethattheorderofthosefiveelementscanbearbitrary.
记住这个这5个元素的顺序任意
Itdoesn'tmatterwhatvaluesaresetbeyondthereturnedlength.
你返回长度之后是什么并不重要
Clarification:
澄清
Confused why the returned value is an integer but your answer is an array?
混淆:为什么要求返回一个值,你却返回一个数组?
Note that the input arrayis passed inbyreference, 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)
num通过引用传入
int len = removeElement(nums, val);
// any modification to nums in your function would be known by the caller.
调用者知道你的函数对nums的修改
// using the length returned by your function, it prints the first len elements.
使用你的函数返回的length,可以打印出前几个元素
for (int i = 0; i < len; i++) {
print(nums[i]);
}
代码
class Solution {
publicintremoveElement(int[] nums, int val) {
int len = nums.length;
int reLen = 0 ;
for(int i = 0 ;i<len;i++)
{
int num = nums[i];
if(num!=val)
{
nums[reLen++] = num;
}
}
return reLen;
}
}
题目Given an array nums and a value val, remove all instances of that value in-place and return the new length.给定一个数组num和一个值,在这个数组中删除这个值得全部实例并且返回新的长度Do not allocate extra space for another array, ...