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.
1、第一次接触双指针,先贴上我的代码,再贴上别人的代码。就是不知道这样的博客算不算原创?
2、传进去的参数n不一定是数组的长度,不能用'\0'判断循环结束的条件
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int i,j;
j=0;
for(i=0;i<n;i++)
{
if(A[i]!=elem)
{
A[j]=A[i];
j++;
}
else
{
while(A[i]==elem&&i<n)
{
i++;
}
if(i==n)
return j;
A[j]=A[i];
j++;
}
}
return j;
}
};
别人的代买,原文地址 点击打开链接
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int pi=0;
for(int i=0;i<n;i++){
if(elem!=A[i]){
A[pi++]=A[i];//不用交换
}
}
return pi;
}
};