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]);
}
今天又是一道简单难度的题,题目要求是这样的:输入一个整数数组nums和一个值val,要求在原数组的基础上去除所有和val相等的值。
emmmm又是一道“原地”处理数组的问题,最近力扣出了好多类似的问题啊……
题目还是比较简单的,大体思路如下:
先定义一个len用来保存当前保留的数组的长度,初始值当然是输入数组nums的长度。
再使用一个index索引遍历数组。
如果当前判断的元素和val相等,那么我们就要把它“去除”,具体怎么去除呢?
因为去除了一个元素,所以我们保留的数组的长度就减一,即len–,此时我们在遍历时,数组的最后一个元素就不会被遍历到,也就是说,我们去除了数组的最后一个元素。既然这样,那么我们只需要将要去除的元素与当前数组最后一个元素进行交换即可。
但是,别忘了,题目中说,数组后面的元素是什么样子它根本不关心,只要我们保留的数组符合要求即可,那么我们也就没有必要真的进行交换,只需要用当前数组的最后一个元素覆盖当前位置就可以了。
举个例子,比如nums=[1, 2, 3, 2, 4, 5], val=2
初始状态:
此时1 != 2,所以index++,继续向后遍历,因为2 == 2,所以将len指向的元素赋值给当前index指向的元素,同时len–
然后此时5 != 2,index++
3 != 2,继续向后遍历
这个时候发现2需要被去除,所以将4赋值给index所指向的位置,len–
此时index所指的元素不等于val,而且index与len重合,循环结束。
所以最终得到的结果为:[1, 5, 3, 4]
具体的实现代码如下:
/**
* @author: LittleWang
* @date: 2021/4/19
* @description:
*/
public class Solution {
public int removeElement(int[] nums, int val) {
int len = nums.length;
if(len == 0)
return 0;
int index = 0;
while(index < len) {
if(nums[index] == val) {
nums[index] = nums[len-1];
len--;
}
else {
index++;
}
}
return len;
}
}
问题解决,提交结果如下: