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

Remove Duplicates from Sorted Array II ——LeetCode

时间:2015-06-07 21:30:06      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

题目大意:给定一个排好序的数组,有重复元素,要求返回新数组长度,新数组中重复元素只能出现两次,新长度后面的是什么无所谓。

解题思路,从前向后遍历,记录一个newLen变量,重复元素记录两次,非重复元素就直接copy到新数组应有的下标处。

    public int removeDuplicates(int[] nums) {
        if(nums==null||nums.length==0){
            return 0;
        }
        int newLen=0;
        for(int i=0;i<nums.length;i++){
            int pos=i;
            nums[newLen++]=nums[i];
            while(i<nums.length-1&&nums[i]==nums[i+1]){
                i++;
            }
            if(pos==i)
                continue;
            nums[newLen++]=nums[i];
        }
        return newLen;
    }

 

Remove Duplicates from Sorted Array II ——LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4559083.html

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