【LeetCode】27. Remove Element (2 solutions)

时间:2022-07-30 17:02:40

Remove Element

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.

解法一:

常规做法,设置一个新A数组的下标ind。

遍历过程中遇到elem就跳过,否则就赋给新A数组下标对应元素。缺点是有多余的赋值。

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

【LeetCode】27. Remove Element (2 solutions)

解法二:最优美的解法,当遍历过程中遇到elem,就用末尾的元素来填补。

这样甚至遍历不到一次。

注意:从末尾换过来的可能仍然是elem,因此i--,需要再次判断。

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

【LeetCode】27. Remove Element (2 solutions)