Remove Element

Q:

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.

A:

 

找到左边第一个等于elem的值,找到右边第一个不等于elem的值,两者互换,搞定

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 l = 0;
        int r = n - 1;
        while (l <= r) {
            while (A[l] != elem && l <= n - 1) {
                ++l;
            }
            while (A[r] == elem && l >= 0) {
                --r;
            }
            if (l < r && l <= n - 1 && r >= 0) {
                swap(A[l], A[r]);
            }
        }
        return l;
    }
};

 

posted @ 2013-06-16 21:33  dmthinker  阅读(90)  评论(0)    收藏  举报