LeetCode --- Remove Element

题目链接

题意:给出长度为n的数组,和整数elem, 要求删除数组中存在的elem,返回最终的数组长度。

附上代码:

 1 class Solution {
 2 public:
 3     int removeElement(int A[], int n, int elem) {
 4         // "front" and "back" keep trace of array A from the front 
 5         //  and the back seperately
 6         // "count" holds the number of "elem" in array A
 7         int front = 0, back = n - 1, count = 0;
 8         while (true) {
 9             while (back >= 0 && A[back] == elem) {
10                 count++;
11                 back--;
12             }
13             while (front < n && A[front] != elem) front++;
14             if (front > back) break;
15             swap(A[front], A[back]);
16             count++;
17             front++, back--;
18         }
19         return n - count;
20     }
21 };

 

posted on 2014-06-08 21:05  Stomach_ache  阅读(154)  评论(0编辑  收藏  举报

导航