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.
"Problem Analysis"
On the basis of the previous topic, the subject changed a little. Each number can appear only once in the previous topic, and each number in this topic is allowed to appear two times.
Ideas
Recall that in the title of the Remove duplicates from Sorted array, an ingenious method is to set up two subscript I and j,i to iterate over the array, and J to indicate the position of the last element of the element that is not repeating in the array. So also in this topic we set up such two variables, indicating that at this point J is used to indicate the last position of the element in the array with no more than 2 repetitions. How do we know how many times an element repeats itself? Do you want to set a variable to record how many times the current element recurs? A very clever way is to compare the current element nums[i] is the same as the previous element nums[j-1], if not the same nums[++j] = nums[i], otherwise the current element will be more than 2 times the number of occurrences, continue to iterate over the array.
The process is as follows:
- Num[i] equals nums[j-1]; i++;
- Nums[i] Not equal to nums[j-1]; NUMS[++J] = nums[i]; i++;
- Num[i] Not equal to num[j-1]; NUMS[++J] = nums[i]; i++;
- Num[i] equals num[j-1]; i++;
- Num[i] Not equal to num[j-1]; NUMS[++J] = nums[i];
"Java Code"
1 Public classSolution {2 Public intRemoveDuplicates (int[] nums) {3 if(Nums.length <= 2)4 returnnums.length;5 intj = 1;6 for(inti=2; i<nums.length; i++) {7 if(Nums[j-1]! =Nums[i])8NUMS[++J] =Nums[i];9 }Ten returnJ+1; One } A}
Leetcode OJ Remove duplicates from Sorted Array II