leetcode 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.

第一种解法是将与elem相等的元素都换到后面去

int removeElement(int A[], int n, int elem){
    if(n == 0) return 0;
    int left = 0 , right = n-1;
    while (left <= right) {
        if (A[left]!=elem) left++;
        else{
            if (A[right] !=elem) {
                swap(A[left],A[right]);
                left++;right--;
            }else{
                right--;
            }
        }
    }
    return left;
}

第二种解法是将与elem不相等的元素换到前面去

int removeElement(int A[], int n, int elem){
    int start = 0;
    for (int i = 0; i < n ; ++ i) {
        if (A[i]!=elem)  A[start++] = A[i];
    }
    return start;
}

 

posted @ 2014-03-27 18:10  OpenSoucre  阅读(180)  评论(0编辑  收藏  举报