# Ordered array de-2--remove duplicates from Sorted array II

Source: Internet
Author: User
Tags repetition

https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

Remove duplicates from Sorted Array II

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

Related Keywords:

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.