首页 > 其他 > 详细

LeetCode "Remove Element"

时间:2014-07-18 19:01:03      阅读:336      评论:0      收藏:0      [点我收藏+]

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:

bubuko.com,布布扣
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

LeetCode "Remove Element",布布扣,bubuko.com

LeetCode "Remove Element"

原文:http://www.cnblogs.com/tonix/p/3853316.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!