Topic:
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 =, with the first 5
five elements of nums being 1
, 1
2
2
,, and 3
. It doesn ' t matter what are you leave beyond the new length.
Idea: Record the number of times for each number, and maintain the position of the new array.
Public classSolution { Public intRemoveDuplicates (int[] nums) { if(Nums.length = = 0) return0; intWalker = 1;//the number of each intCount = 1;//total number of classes intloc = 1;//positioning for(inti = 1; i < nums.length; i++){ if(Nums[i] = = Nums[i-1]){ if(Walker < 2) {Walker++; Count++; }Else{//occurrences more than 2 timeswalker++; Continue; } }Else{Walker= 1;//new numbers appearcount++; } Nums[loc]=Nums[i]; Loc++; } returncount; }}
[Leetcode-java] Remove duplicates from Sorted Array II