Title:
Follow up for "Remove duplicates":
What if duplicates is allowed at the 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
, < Code style= "PADDING:2PX 4px; Color:rgb (199,37,78); Background-color:rgb (249,242,244) ">2 , 2
and 3
. It doesn ' t matter what are you leave beyond the new length.
Test Instructions:
Along with the question "Remove duplicates":
What if the duplicate element is allowed to occur up to two times?
Like what:
Given an ordered array nums = [1,1,1,2,2,3]
,
Your function should returnlength =5
1 ,&NBSP; Code style= "line-height:30px; PADDING:2PX 4px; Color:rgb (199,37,78); Background-color:rgb (249,242,244) ">1 ,&NBSP; Code style= "line-height:30px; PADDING:2PX 4px; Color:rgb (199,37,78); Background-color:rgb (249,242,244) ">2 ,&NBSP; Code style= "line-height:30px; PADDING:2PX 4px; Color:rgb (199,37,78); Background-color:rgb (249,242,244) ">2 and 3
The remaining elements after the new length of the array do not matter.
Algorithm Analysis:
Put the first two repeating elements in the list, and then jump to the next different element to continue with the above operation. Finally, the list element is added back into the array
AC Code:
<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]); 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>
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Remove duplicates from Sorted Array II