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.
给定一个数组nums和一个数值val,将数组中所有等于val的元素删除,并返回剩余的元素个数。
-如 nums=[3,2,2,3],val=3;
-返回2,且nums中前两个元素为2
注:arbitray:随意的、任意的
in-place:原状
allocate:分配
方法1:
思路:1、遍历数组,如果值与传来的值相等,count++,最后用length-count即为剩余数组的长度
2、不允许新开空间,但是不在乎操作后的数组是什么,所以,可以在需要移除的位置保存一个与移除值不等的任意元素,当遍历到移除位置之后第一个非移除元素时,与上一次需要移除位置的元素交换位置
因为需要遍历,时间复杂度为O(n),不需要开辟空间,空间复杂度为O(1)
class Solution {
public int removeElement(int[] nums, int val) {
int rvCount=0;
int rvIndex=-1;
for(int i=0;i<nums.length;i++){
if(nums[i]==val){
nums[i]=val+1;
rvCount++;
if(rvIndex==-1)
rvIndex=i;
}else{
if(rvIndex!=-1&&rvIndex<i){
swap(nums,rvIndex,i);
rvIndex++;
}
}
}
return nums.length-rvCount;
}
private void swap(int[]arry,int l,int r){
if(arry[l]==arry[r])
return;
int temp=arry[l];
arry[l]=arry[r];
arry[r]=temp;
}
}
方法二:
只需要将不等于val的值放到等于val位置,不需要额外开辟空间
时间复杂度O(n)
空间复杂度O(1),只使用了临时变量k
class Solution {
public int removeElement(int[] nums, int val) {
int k=0;//nums[0,k)为不包含val的元素
//for循环中,当遍历到i时,从[0,count]为不包含val的元素
for(int i=0;i<nums.length;i++){
if(nums[i]!=val){
if(i!=k){
nums[k++]=nums[i];
}else{
k++;
}
}
}
return k;
}
}