leetcode Remove Element

OpenSoucre發表於2014-03-27

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;
}

 

相關文章