【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         if (n == 0) return 0;
 5         int i, j;
 6         for (i = 0, j = 1; j < n; ++j) {
 7             if (A[i] != A[j]) {
 8                 A[++i] = A[j];
 9             }
10         }
11         return i + 1;
12     }
13 };
View Code

 注意特殊处理数组为空的情况。

posted @ 2014-03-16 16:29  小菜刷题史  阅读(151)  评论(0)    收藏  举报