Remove Duplicates from Sorted Array II

来源:互联网 发布:java web程序开发入门 编辑:程序博客网 时间:2024/05/18 01:58
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].


解题思路:这题允许最多出现2次,在删除的基础上可以设置个数变量进行控制。


#include<iostream>using namespace std;class Solution {public:    int removeDuplicates(int A[], int n) {       if(n==0)       return 0;       int cs = 1;       int j = 1;       for(int i=1;i<n;++i){       if(A[i]==A[i-1]){   cs++;   if(cs>=3)       continue;       }else{       cs=1;       }       A[j++]=A[i];       }       return j;    }};int main(){int a[9]={1,1,1,2,2,2,3,3,3};Solution s;int len = s.removeDuplicates(a,9);for(int i=0;i<len;++i)cout<<a[i]<<" ";cout<<endl;return 0;}


0 0