您的位置:首页 > 其它

【leetcode】Remove Element (easy)

2015-03-31 16:23 309 查看
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.

思路:

s记录下一个判断位置, e记录结束位置,把前面的待排除元素与后面要保留的元素互换。

int removeElement(int A[], int n, int elem) {
int s = 0, e = n - 1;
while(s <= e)
{
if(A[e] == elem) //末尾待删 直接删除
{
e--;
continue;
}
if(A[s] == elem)
{
A[s++] = A[e--];
}
else
{
s++;
}
}
return e + 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: