Remove Duplicates from Sorted Array II -- Leetcode

来源:互联网 发布:2016qq钓鱼网站源码 编辑:程序博客网 时间:2024/06/10 19:49

Remove Duplicates from Sorted Array II

12.21 2014

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

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


总结:

1. 当长度不超过2时,无论如何都会符合条件要求

2. 应从第三个element (i=2) 开始进行比较,index也应该从2开始

3. 应该先覆盖了以后再进行index的更新,因为index本身就是从需要被覆盖的位置开始
 

0 0
原创粉丝点击