(Daily algorithm) LeetCode --- Remove Duplicates from Sorted Array II (delete duplicate element II)

Source: Internet
Author: User

(Daily algorithm) LeetCode --- Remove Duplicates from Sorted Array II (delete duplicate element II)
Remove Duplicates from Sorted Array II

Leetcode

Question:

Follow up for "Remove Duplicates ":
What if duplicates are allowed at most twice?

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

Your function shocould return length = 5, and A is now [, 3].

Given an ordered table, each element can appear at most twice. Delete unnecessary elements and return the number of remaining elements.

Ideas:

Two pointers, one pointing to the next location in a valid position(index)And the other is used to traverse elements.(i). The two pointers are invalid elements.

Judge at this timeiElements andindex - 2Whether the elements to be pointed to are the same.

Same: Description iThe pointing element is redundant and invalid. iMove back. Different: Description iThe pointing element is valid, that is, the number of occurrences is no more than two times. In this case, use iReplace indexYou can. indexIf you need to move it back, you can view it in the Markdown document: Click to open the link. The Code is as follows:
 
 
  1. class Solution {
  2. public:
  3. int removeDuplicates(int A[], int n) {
  4. Int deleted = 0; // Number of deleted elements
  5. If (n <3) // contains a maximum of 2 elements.
  6. return n;
  7. Int index = 2; // The location may be invalid.
  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. };

Related Article

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.