码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Remove Duplicates from Sorted Array II

时间:2014-08-05 00:24:38      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   ar   cti   

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) {
        vector<int> Acopy(A,A+n);
         if(n<=2)
             return n;
        int res = n;
        int temp = A[0];
        int tempNum = 1;
        int j = 1;
        for(int i=1;i<n;i++){
            if(Acopy[i]==temp && tempNum<2){
                A[j++]=Acopy[i];
               tempNum++;
            }else if(Acopy[i]==temp && tempNum>=2){
             tempNum++;
             res--;
            }else if(Acopy[i]!=temp){
              temp = Acopy[i];
              tempNum = 1;
              A[j++]=Acopy[i];
            }
            
        
        }//end for
        return res;
    }
};

关键数组A中的前res个元素要变化成需要的结果。

[LeetCode] Remove Duplicates from Sorted Array II,布布扣,bubuko.com

[LeetCode] Remove Duplicates from Sorted Array II

标签:style   blog   color   os   io   for   ar   cti   

原文地址:http://www.cnblogs.com/Xylophone/p/3891161.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!