您的位置:首页 > 其它

LeetCode Remove Element

2014-03-09 19:52 337 查看


Remove Element

 Total Accepted: 9749 Total
Submissions: 30209My Submissions

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.

题目不要求原顺序,但是其实也可以保持原顺序。

T。T我好像歧视自己的代码,总怎么看怎么不爽。。。

乱序版

class Solution {
public:
int removeElement(int A[], int n, int elem) {
int i = 0;
while (i < n) {
if (A[i] == elem) {
A[i] = A[n - 1];
--n;
}
else
++i;
}
return n;
}
};

顺序版
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int num=0,i;
for(i=0;i<n;++i)
if(A[i]!=elem)A[num++]=A[i];
return num;
}
};
// blog.csdn.net/havenoidea
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode Oj