Leetcode-26. Delete duplicates in a sorted array

Source: Internet
Author: User

Given a sorted array, you need to delete the repeating elements in place so that each element appears only once, returning the new length of the array after removal.

Instead of using extra array space, you must modify the input array in place and complete it with O (1) Extra space.

Example 1:

Nums 1 2 . You do not need to consider elements that are beyond the new length in the array.

Example 2:

Given   0 1 2 3 4 . You do not need to consider elements that are beyond the new length in the array.

Description

Why is the return value an integer, but the answer to the output is an array?

Note that the input array is passed in a "reference" manner, which means that modifying the input array in the function is visible to the caller.

You can imagine the internal operation as follows:

The nums is passed in a "reference" manner. That is, do not make any copy of the argument int len = removeduplicates (nums);//Modifying an input array in a function is visible to the caller. Depending on the length returned by your function, it prints all the elements within that length range in the array. for (int i = 0; i < len; i++) {print (nums[i]);}
Idea: Use quick and slow pointer, fast pointer traversal, slow pointer record number of non-repeating elements, each encounter new elements according to the slow pointer to the corresponding position. Code:
Class Solution:    def removeduplicates (self, Nums): "" "        : Type Nums:list[int]        : Rtype:int        "        "" If not nums:            return 0        k = 0        for i in range (1, Len (nums)):            if nums[k]! = Nums[i]:                k + = 1                nums[k]  = Nums[i]        return k + 1if __name__ = = ' __main__ ':    s = solution ()    s.removeduplicates ([0, 0, 1, 1, 1, 2, 2, 3, 3, 4])

  

Leetcode-26. Delete duplicates in a 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.