您的位置:首页 > 其它

leetcode: Remove Element

2014-12-01 22:58 169 查看
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.

解法一:

class Solution {
public:
int removeElement(int A[], int n, int elem) {
int nl, i;

if (n == 0) {
return n;
}

nl = n;
for (i = 0; ;) {

if (A[i] == elem) {
while (A[nl-1] == elem) {
//nl--;
if (i == nl - 1) {
return nl - 1;
}
nl--;
}

A[i] = A[nl-1];
nl--;
}

i++;
if (i >= nl) {
break;
}
}

return nl;
}
};

解法二(很巧妙的解法)

class Solution {
public:
int removeElement(int A[], int n, int elem) {
int len, i, pos;

if (n == 0) {
return n;
}

len = n;
for (i = 0, pos = 0; i < n; i++) {/* just like double arrays */
if (A[i] == elem) {
len--;
} else {
A[pos++] = A[i];
}
}

return len;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: