[面试真题] LeetCode:Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example, 

Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         int tail  = 0;
 7         int rtn = n;
 8         for(int i=1; i<n; i++){
 9             while(i<n && A[i] == A[tail]){
10                 i++;
11                 rtn--;
12             }
13             A[++tail] = A[i];
14         }
15         return rtn;
16     }
17 };

Run Status: Accepted!
Program Runtime: 68 milli secs

Progress: 160/160 test cases passed.
!红色部分判定一开始没有加上,导致部分用例没能通过。
[0,0,0,1,2,2,4,4]        输出:[0,1,2]
[-3,-3,-2,-1,-1,0,0,0,0,0]      输出:[-3,-2,-1]
posted @ 2013-05-13 20:24  infinityu  阅读(150)  评论(0编辑  收藏  举报