【leetcode】Remove Element (easy)

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.

 

思路:

s记录下一个判断位置, e记录结束位置,把前面的待排除元素与后面要保留的元素互换。

int removeElement(int A[], int n, int elem) {
    int s = 0, e = n - 1;
    while(s <= e)
    {
        if(A[e] == elem) //末尾待删 直接删除
        {
            e--;
            continue;
        }
        if(A[s] == elem)
        {
            A[s++] = A[e--];
        }
        else
        {
            s++;
        }
    }
    return e + 1;
}

 

posted @ 2015-03-31 16:23  匡子语  阅读(151)  评论(0编辑  收藏  举报