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].

 

这道题跟Remove Duplicates from Sorted Array比 较类似,区别只是这里元素可以重复出现至多两次,而不是一次。其实也比较简单,只需要维护一个counter,当counter是2时,就直接跳过即可, 否则说明元素出现次数没有超,继续放入结果数组,若遇到新元素则重置counter。总体算法只需要扫描一次数组,所以时间上是O(n),空间上只需要维 护一个index和counter,所以是O(1)。代码如下: 

  1. public int removeDuplicates(int[] A) {  
  2.     if(A==null || A.length==0)  
  3.         return 0;  
  4.     int idx = 0;  
  5.     int count = 0;  
  6.     for(int i=0;i<A.length;i++)  
  7.     {  
  8.         if(i>0 && A[i]==A[i-1])  
  9.         {  
  10.             count++;  
  11.             if(count>=3)  
  12.                 continue;  
  13.         }  
  14.         else  
  15.         {  
  16.             count = 1;  
  17.         }  
  18.         A[idx++]=A[i];  
  19.     }  
  20.     return idx;  
  21. }  

这种简单数组操作的问题在电面中比较常见,既然简单,所以出手就要稳,不能出错,还是要保证无误哈。

 

 

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if (n <= 2) return n;
        
        int k = 1;
        for (int i = 2; i < n; i++) {
            if (A[i] == A[k] && A[i] == A[k-1]) continue;
            A[++k] = A[i];
        }
        
        return k + 1;        
    }
};

 

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if (n <= 2) return n;
        
        int k = 2;
        for (int i = 2; i < n; i++) {
			if(A[i] != A[k-2])
				A[k++] = A[i];
        }
        
        return k;        
    }
};

 

posted on 2015-01-10 22:15  风云逸  阅读(41)  评论(0)    收藏  举报