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

【Leetcode】Remove Duplicates from Sorted Array II

时间:2014-08-20 13:53:12      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:blog   os   io   for   ar   art   cti   div   

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

 

双指针的思路,但是这里容许两个重复,所以判断条件修改一下。

 

1st (5 tries)

class Solution 
{
public:
    int removeDuplicates(int A[], int n) 
    {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int i,j,k,count;
        for(i = 0;i < n;++i)
        {
            count = 0;
            int tmp = A[i];
            j = i+2;
            while(j < n&&A[j] == tmp)
            {
                j++;
                count++;
            }
            if(count == 0)
                ;
            else
            {
                for( k = j; k < n;++k)
                {
                    A[k-count] = A[k];
                }
            }
            n -= count;
        }
        return n;
    }
};

  

2nd(3 tries)

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

  

【Leetcode】Remove Duplicates from Sorted Array II,布布扣,bubuko.com

【Leetcode】Remove Duplicates from Sorted Array II

标签:blog   os   io   for   ar   art   cti   div   

原文地址:http://www.cnblogs.com/weixliu/p/3924315.html

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