首页 > 代码库 > Leetcode 线性表 Remove Duplicates from Sorted Array II

Leetcode 线性表 Remove Duplicates from Sorted Array II

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


Remove Duplicates from Sorted Array II

 Total Accepted: 10649 Total Submissions: 35325

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一样,不过要设置一个计数变量,表示当前值出现的次数

出现次数少于2可以加入到新数组,多于2则不可以。每次遇到一个新变量要把计数变量重新设置为1,加入新数组要加1 

复杂度:时间O(n), 空间O(1)

相关题目:


class Solution {
public:
    int removeDuplicates(int A[], int n){
    	if (n < 1) return 0;
    	int c = 1;
    	int j = 1;
    	
    	for(int i = 1; i < n; i++){
    		if (A[i] == A[i - 1]){
    			if(c < 2){
    				A[j++] = A[i];
    				c++;
    			}
    		}else{
    			A[j++] = A[i];
    			c = 1;
    		}
    	}
    	return j;
    }
};