标签: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 1
, 1
, 2
, 2
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中的前五个元素为1
, 1
, 2
, 2
and 3
.数组新的长度后面剩余的元素无所谓。
将前两个重复元素放入list中,然后跳转到下一个不同元素,继续上述操作。最后将list元素重新添加到数组中
<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