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

[LeetCode][Java] Remove Duplicates from Sorted Array II

时间:2015-07-18 15:40:45      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:leetcode   java   remove duplicates fr   

题目:

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.

题意:

伴随着问题"Remove Duplicates":

如果重复的元素最多允许出现两次呢?

比如:

给定有序数组 nums = [1,1,1,2,2,3],

你的函数应该返回 length = 5, 数组nums中的前五个元素为1122 and 3.数组新的长度后面剩余的元素无所谓。

算法分析:

将前两个重复元素放入list中,然后跳转到下一个不同元素,继续上述操作。最后将list元素重新添加到数组中

AC代码:

<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution 
{
    public int removeDuplicates(int[] nums) 
    {
		if(nums==null||nums.length==0) return 0;
    	ArrayList<Integer> list = new ArrayList<Integer>();
		for(int i=0;i<nums.length;i++)
		{
			if(i==nums.length-1)
			{
				list.add(nums[i]);
				break;
			}
			if(nums[i]==nums[i+1])
			{
				while(nums[i]==nums[i+1])
				{
					i++;
					if(i+1>nums.length-1)
						break;
				}
				list.add(nums[i]);
				list.add(nums[i]);
			}
			else
				list.add(nums[i]);
		}
		for(int i=0;i<list.size();i++)
			nums[i]=list.get(i);
    	return list.size();
    }
}</span>


版权声明:本文为博主原创文章,转载注明出处

[LeetCode][Java] Remove Duplicates from Sorted Array II

标签:leetcode   java   remove duplicates fr   

原文地址:http://blog.csdn.net/evan123mg/article/details/46942543

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