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

Source: Internet
Author: User

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 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.


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. imove 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 . indexneed to move back
can be viewed in the markdown documentation: Click to open the link code as follows:
  1. class Solution {
  2. public:
  3. int removeDuplicates(int A[], int n) {
  4. int deleted = 0; //已经删除的元素个数
  5. if(n < 3) //最多含有2个元素,一定满足题意
  6. return n;
  7. int index = 2; //可能不合法的位置
  8. for(int i = 2; i < n; i++)
  9. {
  10. if(A[i] != A[index - 2] )
  11. A[index++] = A[i];
  12. }
  13. return index;
  14. }
  15. };

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