# (Daily algorithm) Leetcode---Remove duplicates from Sorted Array II (remove duplicate element II)

Source: Internet
Author: User

Remove duplicates from Sorted Array II

`Leetcode`

Topic:

What if duplicates is allowed at the most twice?

For example,
Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].

Given an ordered table, each element appears up to two times. Remove the extra elements and return the number of remaining elements.

Ideas:

Two pointers, one pointing to the next position in the legal position `（index）` , and the other for traversing the element `(i)` . The invalid element is between two pointers.

This is the time `i` to determine whether the element pointed to is the same as `index - 2` the element pointed to.

• Same: `i` the description points to an element that is superfluous and invalid. `i`move back.
• Not the same: indicates that `i` the element pointed to is valid, that is, not more than 2 occurrences. At this point, `i` replace it `index` . `index`need to move back
can be viewed in the markdown documentation: Click to open the link code as follows:
```

`class Solution {`

`public:`

` int removeDuplicates(int A[], int n) {`

` int deleted = 0; //已经删除的元素个数`

` if(n < 3) //最多含有2个元素，一定满足题意`

` return n;`

` int index = 2; //可能不合法的位置`

` for(int i = 2; i < n; i++)`

` {`

` if(A[i] != A[index - 2] )`

` A[index++] = A[i];`

` }`

` return index;`

` }`

`};`

```

(Daily algorithm) Leetcode---Remove duplicates from Sorted Array II (remove duplicate element 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.