[LeetCode] Remove Duplicates from Sorted Array II

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]

 

加一个变量记录一下元素出现的次数即可。这题因为是已经排序的数组,所以一个变量即可解
决。如果是没有排序的数组,则需要引入一个 hashmap 来记录出现次数。

 

方法1  用A[i] 和 A[index] 比较,同时,搞一个计数器

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if(n == 0)
 5         return 0;
 6         
 7         int index = 0;
 8         int cnt=1;
 9         for(int i = 1; i<n; i++)
10         {
11             if(A[index] != A[i])
12             {
13                 index++;
14                 A[index]=A[i];
15                 cnt = 1;
16             }
17             else
18             {
19                 if(cnt ==1)
20                 {
21                     index++;
22                     A[index]=A[i];
23                     cnt +=1;
24                 }
25             }
26                 
27         }
28         return index + 1;
29     }
30 };

方法2  用A[i] 和 A[index-1] 比较,此方法可推广至最多允许k个数的情况

 1 class Solution {
 2     public:
 3         int removeDuplicates(int A[], int n) {
 4             if (n <= 2) return n;
 5             int index = 2;//此方法可推广至最多允许k个数的情况,修改inde的值即可
 6             for (int i = 2; i < n; i++){
 7                 if (A[i] != A[index - 2])
 8                     A[index++] = A[i];
 9             }
10             return index;
11         }
12 };

 

posted @ 2014-06-14 11:03  穆穆兔兔  阅读(213)  评论(0编辑  收藏  举报