[Leetcode 30] 80 Remove Duplicates From Sorted Array II

Probelm:

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array A = [1,1,1,2,2,3],

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

 

Analysis:

One pass algorithm, with the help of an extra counter which keeps recoreds of the number of current element's occurance.

Pay special attention that the returned value is the length of the array which is 1 greater than the nn's last value

 

Code:

 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         if (n == 0) return n;
 7         
 8         int nn = 0, cnt = 1;
 9         for (int i=1; i<n; i++) {
10             if (A[i] != A[nn]) {
11                 A[++nn] = A[i];
12                 cnt = 1;
13             } else if (A[i] == A[nn] && cnt==1) {
14                 A[++nn] = A[i];
15                 cnt = 2;
16             }
17         }
18         
19         return nn+1;
20     }
21 };
View Code

 

 

Attention:

posted on 2013-05-20 07:44  freeneng  阅读(119)  评论(0编辑  收藏  举报

导航