码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode-JAVA] Remove Duplicates from Sorted Array II

时间:2015-05-17 21:40:55      阅读:122      评论: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.

 

思路:记录每个数字的次数,并且维护新数组的位置。

 

public class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums.length == 0)
            return 0;
            
        int walker = 1; //每个的数量
        int count = 1; //总类数量
        int loc = 1; //定位

        for(int i = 1 ; i < nums.length ; i++){            
            if(nums[i] == nums[i-1]){
                if(walker < 2){
                    walker++;
                    count++;
                }else{    //出现次数大于2次
                    walker++;
                    continue;
                }
            }else{
                    walker = 1;    //出现新数字
                    count++;
            }
            nums[loc] = nums[i];
            loc++;
        }
        
        return count;
    }
}

 

[LeetCode-JAVA] Remove Duplicates from Sorted Array II

标签:

原文地址:http://www.cnblogs.com/TinyBobo/p/4510441.html

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