代码改变世界

leetcode - Remove Element

2013-10-20 10:06  张汉生  阅读(108)  评论(0编辑  收藏  举报

 1 class Solution {
 2 public:
 3     int removeElement(int A[], int n, int elem) {
 4         // Note: The Solution object is instantiated only once and is reused by each test case.
 5         for (int i=0; i<n; i++){
 6             while (n>0&&A[n-1]==elem){
 7                 n--;
 8             }
 9             if (i>=n){
10                 break;
11             }
12             if (A[i]==elem){
13                 A[i] = A[n-1];
14                 n--;
15             }
16         }
17         return n;
18     }
19 };