Remove duplicates from Sorted Array II
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.
https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
Deletes an array that repeats three or more times or more than three occurrences.
Two variables record the last and previous values, compare, if there is greater than or equal to three times, write down the subscript.
Remove them from the back and forth, so that they do not disrupt the order of the subscripts.
1 /**2 * @param {number[]} nums3 * @return {number}4 */5 varRemoveDuplicates =function(nums) {6 varAremove =[], I, previous, previous2;7 for(i = 0; i < nums.length; i++){8 if(Nums[i]!==Previous) {9 // First timeTen}Else if(Nums[i] = = = Previous && nums[i]!==previous2) { One //Duplicate A}Else{ - //duplicate more than - Aremove.push (i); the } -Previous2 =previous; -Previous =Nums[i]; - } + for(i = aremove.length-1; I >= 0; i--){ -Nums.splice (Aremove[i], 1); + } A returnnums.length; at};
Another more concise approach, open a variable index, each time the correct results are placed in the position labeled Index, index++, after traversing the index is the length of the target array.
1 /**2 * @param {number[]} nums3 * @return {number}4 */5 varRemoveDuplicates =function(nums) {6 varindex = 0, I, Previous, previous2;7 for(i = 0; i < nums.length; i++){8 if(Nums[i]!==Previous) {9nums[index++] =Nums[i];Ten}Else if(Nums[i] = = = Previous && nums[i]!==previous2) { Onenums[index++] =Nums[i]; A } -Previous2 =previous; -Previous =Nums[i]; the } - returnindex; -};
[Leetcode][javascript]remove duplicates from Sorted Array II