Remove Duplicates from Sorted Array

http://oj.leetcode.com/problems/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].

Solution:

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if (n==0) return 0;
 5         int index =0;
 6         for (int i=1;i<n;++i){
 7             if (A[index]!=A[i])
 8                 A[++index]=A[i];
 9         }
10         return index+1;
11     }
12 };

 

 

 

posted @ 2014-02-16 20:28  风云语  阅读(120)  评论(0编辑  收藏  举报