27 Remove Element

时间:2022-06-22 09:17:17

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

题目的要求大概是给定一个数组和一个值,删除数组中所有和该值相同的元素并返回一个新的长度

说一下思路:

可以采用双指针,下标i循环数组,每次都让p_last下标与i一起遍历,当A[i]与给定的value相同的时候,p_last停止,数组长度-1,i继续走将下一个值赋给A[p_last],如果是A[i]与value不同的话,就让p_last+1

具体的代码如下:

 class Solution {
public:
int removeElement(int A[], int n, int elem) {
int length = n;
int p_last = ;
for(int i=;i<n;i++){
A[p_last] = A[i];
if(A[i] == elem)
length--;
else
p_last++;
}
return length;
}
};

或者可以有一个更加直观的理解:

如下面的代码:

 class Solution {
public:
int removeElement(int A[], int n, int elem) {
int length = n;
int p_last = ;
for(int i=;i<n;i++){
if(A[i]==elem){
length--;
}else{
A[p_last] = A[i];
p_last++;
}
}
return length;
}
};

p_last代表当前”新“数组的下标,i循环数组当A[i]!=elem时进行赋值,并将p_last加一”新“数组的下一个元素等待被插入个人认为这种方式解释方式比较直观。