Remove Duplicates from Sorted Array II

来源:互联网 发布:淘宝网电话 编辑:程序博客网 时间:2024/06/16 04:58

自己搞定

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


C++

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


summary:

数组可以in-place的替换,这个一定要掌握。 相当于前面是一个新数组,后面是一个数组。


0 0
原创粉丝点击