现在的位置: 首页 > 综合 > 正文

LeetCode题解:Remove Element

2019年07月25日 ⁄ 综合 ⁄ 共 516字 ⁄ 字号 评论关闭

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.

思路:

左右两个指针依次指向数组开始和结束。左右指针移动,将所有要去掉的元素移入最后。需要注意右边指针的元素很可能也是要移走的元素,对此的处理方法很多。

题解:

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        if (n == 0)
            return 0;
        
        int liter = 0, riter = n - 1;
        while(liter < riter)
        {
            while(A[riter] == elem && riter > liter) --riter;
            if (riter == liter)
                break;
            if (A[liter] == elem)
                swap(A[liter], A[riter]);
            ++liter;
        }
        return A[liter] == elem ? liter : liter + 1;
    }
};


抱歉!评论已关闭.