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

题目:

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

For example,Given sorted arraynums=[1,1,1,2,2,3],

Your function should return length =5, with the first five elements ofnumsbeing1,1,2,2and3. It doesn’t matter what you leave beyond the new length.

题意:

伴随着问题"Remove Duplicates":

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

比如:

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

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

算法分析:

将前两个重复元素放入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]);}elselist.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

相关文章:

你感兴趣的文章:

标签云: