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.
自己做时的想法是:从前往后扫,不是的就放在原来的地方,是的话就把最后一个放过来替换掉,第一次提交出错,原因是换过来后没有继续考虑当前位置的值。
别人的解法
(1)一个数组当做两个用。如果是要移除的元素就跳过,不是的话就从数组开头放起。
别人的:
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)还有的统计移去的个数,每个不移去的相应往左移动。
自己的:
#include <iostream>
using namespace std;
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int p1 = n-1;
int p0 = 0;
while( p0 <= p1 ){
if(A[p0] == elem)
A[p0] = A[p1--];
else
p0++;
}
return p1+1;
}
};
int main(){
int a[6] = {3,3};
Solution s=Solution();
for(int i=0;i<s.removeElement(a,2,3);++i)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
别人的:
class Solution {
public:
int removeElement(int A[], int n, int elem) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i = 0, j = 0;
for(i=0; i<n; )
{
if(A[i] == elem)
{
i++;
}
else
{
A[j] = A[i];
j++, i++;
}
}
return j;
}
};