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,对数组从头到尾顺序遍历一遍,若遇到与给定值相等,则index++,最终得到的index即为所求。
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int index = 0;
int i = 0;
for(;i < n;i++){
if(elem != A[i])
A[index++] = A[i];
}
return index;
}
};