Remove duplicates from Sorted Array II Leetcode problem solving
On the base of the remove duplicates from Sorted array (removing the duplicated number from an ordered array, returning the processed array length), you can make each number repeat at most once, that is, if the number of a number is greater than or equal to 2, 2 of this number should be retained in the results.
Note the point:
- Only the extra space with constants
- Move the number that you want to keep to the front of the array, and the remaining parts do not need to be processed
Example:
Input: Nums = [1,1,1,2,2,3]
Output: 5 ([1,1,2,2,3,3])
Thinking of solving problems
First, remember that the original array is ordered, and then look at the following scenarios:
- [About]
- [1,1,2]
- [1,1,2,2]
- [1,1,2,2,3]
In the process of each insertion, as long as the element to be inserted and the second-to-last element is compared, if the same, ignore, because the first number of the countdown is sandwiched between them, if they are equal, then there will be three numbers equal, if different, can be inserted, because in such cases, at most only the penultimate, The first two counts are equal.
AC Source
class solution(object): def removeduplicates(self, nums): "" : Type Nums:list[int]: Rtype:int " " "Count =0 forIinchRange (len (nums)):ifCount <2 orNums[count-2] = Nums[i]: nums[count] = nums[i] Count + =1 returnCountif__name__ = ="__main__": L = [1,1,1,2,2,3] R = Solution (). RemoveDuplicates (L)assertL = = [1,1,2,2,3,3]assertr = =5
Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.
Leetcode Remove duplicates from Sorted Array II