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

Leetcode#80Remove Duplicates from Sorted Array II

时间:2015-05-16 18:35:41      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:function   beyond   elements   example   public   

Remove Duplicates from Sorted Array II

 Total Accepted: 39950 Total Submissions: 130101My Submissions

Question Solution 


Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1122 and 3. It doesn‘t matter what you leave beyond the new length.


Show Tags

问题分析:去掉重复项,这里的重复是指3个以上,去重是指将3个以上项降为2个,还是使用传入的数组作为目标数组存储去重后结果,同时返回去重后的数组内数据个数


public class Solution {


    public int removeDuplicates(int[] nums) {

        int count=0;

        int midc=0;

        int size=nums.length;

        if(size<=1)

            return size;

        int i;

        for(i=0;i<nums.length-1;i++)

        {   

            if(nums[i]!=nums[i+1])

            {

                midc++;

                if(midc<2)

                {

                    nums[count]=nums[i];

                    count=count+1;

                }

                else

                {

                    nums[count]=nums[i];

                    nums[count+1]=nums[i];

                    count=count+2;

                }

                midc=0;

            }

            else

            {

                midc++;        

            }

        }

        if(midc==0)

        {

            nums[count]=nums[i];

            count++;

        }

        else 

        {

            nums[count]=nums[i];

            nums[count+1]=nums[i];

            count=count+2;

        }

        return count;

    }

}


Leetcode#80Remove Duplicates from Sorted Array II

标签:function   beyond   elements   example   public   

原文地址:http://7061299.blog.51cto.com/7051299/1651909

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