LeetCode, leetcodeoj

Source: Internet
Author: User

LeetCode, leetcodeoj

Link: Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,

Given input array A = [1, 1, 2],

Your function shocould return length = 2, and A is now [1, 2].

The requirement for this question is to delete duplicate elements in an ordered array, so that each number appears only once, and return the new length of the array. Requirement: no additional space is allowed, that is, constant space complexity is required.

The idea of this question is to use two pointers: l and r. l records the positions of non-repeating elements. r traverses the array from the next of l. If the number at the r position is equal to the number at the l position, this number is repeated and not processed. If the number at the r position is not equal to the number at the l position, it indicates that the number is not repeated and must be placed in the next position of the l, and add l to 1.

Time Complexity: O (n)

Space complexity: O (1)

 1 class Solution 2 { 3 public: 4     int removeDuplicates(int A[], int n) 5     { 6         if(n == 0) 7             return 0; 8          9         int l = 0;10         for(int r = 1; r < n; ++ r)11             if(A[r] != A[l])12                 A[++ l] = A[r];13         return l + 1;14     }15 };

Reprinted please note the Source: LeetCode --- 26. Remove Duplicates from Sorted Array

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.