您的位置:首页 > 其它

leetcode 39: Remove Element

2013-01-16 09:06 288 查看
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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i=0, j=n-1;

while( i<=j) {
if( A[i] == elem) {
while( j>=i && A[j] == elem ) j--;
if( j<= i ) break;
A[i] = A[j--];
}
i++;
}

return i;
}
};


public class Solution {
public int removeElement(int[] A, int elem) {
//113251631345465, 1
//check input.
if(A==null || A.length<1) return 0;
int i=-1;
for(int j=0; j<A.length; j++) {
if(A[j]!=elem) {
A[++i] = A[j];
}
}
return i+1;
}
}


//this approach can keep the original order.

class Solution {
public:
int removeElement(int A[], int n, int elem) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int i=-1, j=0;

while(j<n) {
if(A[j]!=elem) {
A[++i] = A[j++];
} else {
++j;
}
}
return i+1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: