https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
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 = 5
, with the first five elements of nums being 1
, 1
, 2
, and 3
. It doesn ' t matter what are you leave beyond the new length.
Test instructions: Ordered array, deduplication, allow up to 2 duplicates
The idea of solving problems: a clever solution. Use two pointers prev and curr to determine if A[CURR] is equal to A[prev], A[prev-1], and if equality means that the Curr pointer is pointing to a 3rd repetition, continue to traverse backwards until unequal, assigning the value of the Curr pointer to a[prev+1], The last prev+1 value is the length of the array. The pre pointer controls the final array form.
1 classSolution:2 #@param {integer[]} nums3 #@return {integer}4 defremoveduplicates (Self, nums):5A=Nums6 ifLen (A) <=2:returnLen (A)#for a maximum of 2 repetitions, the <=2 does not need to be weighed7prev=1;curr=2#using the pre to control the final array, Curr to iterate over the array to determine8 whileCurr<=len (A)-1:9 ifA[curr]==a[prev] andA[curr]==a[prev-1]:#if Curr points to the 3rd repetition, the pre is controlled at the 2nd repetition, and Curr continues to traverseTenCurr+=1 One Else:#If there is no repetition or repetition within 2, the current Curr number is added to the pre, and the pre moves back to hold APrev+=1 -a[prev]=A[curr] -Curr+=1 the returnPrev+1#returns the pre+1, or length, of the final array
Ordered array de-2--remove duplicates from Sorted array II