[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,试图从后往前找一个元素与之交换,如果找不到可以交换的元素,则停止。注意elem如果没有出现,则应该返回n。

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int tmp = 0, len = 0, left = 0, right = n - 1;//0 for 
        for(left = 0;left < n;left++)
        {
            if(A[left] == elem)
            {
                bool flag = false;
                for(int i = right; i > left; i--)
                {
                    if(A[i] != elem)
                    {
                        tmp = A[i];
                        A[i] = A[left];
                        A[left] = tmp;
                        right = i - 1;
                        flag = true;
                        break;
                    }
                }
                if(flag == false)
                    return left;
            }
            else
            {
                if(left == right)
                    return left + 1;
            }
        }
        
        return n;
    }
};
原文地址:https://www.cnblogs.com/changchengxiao/p/3416466.html