Delete ordered array duplicates 1--remove duplicates from Sorted array

Source: Internet
Author: User

https://leetcode.com/problems/remove-duplicates-from-sorted-array/

Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such, all element appear only once and return the new L Ength.

Do the allocate extra space for another array, and you must does this on place with constant memory.

For example,
Given input array nums = [1,1,2] ,

Your function should return length = 2 , with the first of the elements of nums being and 1 2 Respectiv Ely. It doesn ' t matter what are you leave beyond the new length.

Test instructions: Returns the length of the array after the duplicate is deleted (because the sorted array is ordered, so the repetition will only appear in order)

Problem solving idea: Using a pointer J, when I traverse an array backwards, if it encounters a a[j] different from that, will a[i] and a[j+1] exchange, while j=j+1, then I continue to traverse backwards.

1 classSolution:2     #@param {integer[]} nums3     #@return {integer}4     defremoveduplicates (Self, nums):5         ifLen (nums) ==0:return06j=07          forIinchRange (len (nums)):#I iterate through the array to Judge8             ifNUMS[I]!=NUMS[J]:#[0] number first to accept9Nums[i],nums[j+1]=nums[j+1],nums[i]#(the default number of repetitions will get together) if a different number appears again, after J, that is, and num[j+1] interchangeTenJ=j+1 One         returnJ+1#Note: J is the index, starting from 0, the return length requires +1

Delete ordered array duplicates 1--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.