标签: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:
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; } };
LeetCode "Remove Element",布布扣,bubuko.com
标签:style blog http color os art
原文地址:http://www.cnblogs.com/tonix/p/3853316.html