题目描述
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.
方法一:用一个新的index更新迭代数组下标,条件为A[i]!=elem(推荐使用)
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int index = 0;
for(int i=0; i<n; i++){
if(A[i] != elem)
A[index++] = A[i];
}
return index;
}
};
class Solution {
public:
int removeElement(int A[], int n, int elem) {
for(int i=0;i<n;i++)
{
if(A[i] == elem)
{
swap(A[i],A[n-1]);
n--;
i--;
}
}
return n;
}
};
本文介绍两种有效的算法来移除数组中指定值的所有实例,并返回新的长度。第一种方法使用新索引更新数组,第二种方法通过交换元素并递减数组长度实现目标。
656

被折叠的 条评论
为什么被折叠?



