LeetCode "Remove Element"

Since no order requirement, we can simply swap the target value to the last non-target-value in the array - if the last non-target-value is not behind the current index, we are done. I got 1A:

class Solution {
public:
    bool move_back(int A[], int tgt, int n)
    {
        for (int i = n - 1; i >= 0; i--)
        {
            if (A[i] != A[tgt])
            {
                if (i <= tgt)
                {
                    return false; // we are done
                }
                else
                {
                    int tmp = A[i];
                    A[i] = A[tgt];
                    A[tgt] = tmp;
                    return true;
                }
            }            
        }
        return false;
    }
    int removeElement(int A[], int n, int elem) {
        int nCnt = n;
        for (int i = 0; i < n; i++)
        {
            if (A[i] == elem)
            {
                bool bSwap = move_back(A, i, n);
                if (!bSwap)
                {
                    nCnt = i;
                    break;
                }
            }
        }
        return nCnt;
    }
};
View Code
原文地址:https://www.cnblogs.com/tonix/p/3853316.html