Remove Duplicates from Sorted Array II

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

Solution:

由于数组已经排序,所以只需要增加一个变量来记录元素出现的次数;若没有排序,需要使用hash来记录每个元素的出现次数。

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if(0==n) return 0;
 5         int appear =1;
 6         int index =0;
 7         for (int i=1;i<n;++i){
 8             if (A[index]==A[i]){
 9                 if (appear<2){
10                     A[++index]=A[i];
11                     ++appear;
12                 }
13             }else{
14                 A[++index]=A[i];
15                 appear =1;
16             }
17         }
18         return index+1;
19         
20     }
21 };

 

 

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