Leetcode Remove duplicates from Sorted Array II

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.