码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Remove Element"

时间:2014-07-18 17:36:41      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   art   

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"

标签:style   blog   http   color   os   art   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!