首页 > 编程语言 > 详细

leetcode 80 Remove Duplicates from Sorted Array II ----- java

时间:2016-10-16 19:28:37      阅读:180      评论: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.

是第26题的延伸版,26题说的是给一个排序好的数组,然后删掉所有重复的数字,使所有数字只出现1次,然后返回长度。

这道题指的是允许数字最多出现2次。然后求长度len2。并且返回的数组前len2个数应当是整理过之后的数组。

public class Solution {
    public int removeDuplicates(int[] nums) {

        int len = nums.length;
        if( len < 2 )
            return len;
        int flag = nums[0];
        int times = 1;
        int res = len;
        for( int i = 1 , j = 1;i<len;i++){
            if( flag == nums[i] ){
                if( times == 1)
                    times++;
                else{
                    res--;
                    continue;
                }
            }else{
                flag = nums[i];
                times = 1;
            }
            nums[j] = nums[i];
            j++;
        }
        
        return res;
    }
}

 

leetcode 80 Remove Duplicates from Sorted Array II ----- java

原文:http://www.cnblogs.com/xiaoba1203/p/5967229.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!