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

LeetCode --- Remove Element

时间:2014-06-09 13:38:05      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

题目链接

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

附上代码:

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

 

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

LeetCode --- Remove Element

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/Stomach-ache/p/3776756.html

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