Remove Element [LEETCODE]

Remove Element

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

 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(elem == A[i] && i + 1 <= n) {
 7                 A[i] = A[n - 1];
 8                 n--;
 9             }
10         }
11         return n;
12     }
13 };

Remember to ensure that i + 1 <= n,  not <, considering the last element 


posted @ 2013-10-21 16:21  昱铭  阅读(126)  评论(0)    收藏  举报