Leetcode Remove duplicates from Sorted Array

Source: Internet
Author: User

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 A = [1,1,2] ,

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

The same array, go heavy, and keep the linear space.

All said the problem is not difficult, but the problem is always done wrong, the beginning of the double cycle, time expired

Later read the answer, with two pointers, a point to be compared with the current element, a point to be compared to the following number, if the following number and this number is equal, then the pointer backward push, straight to find a different number, then move this number, and then continue to compare, the back of the number are moved over.

1  PackageRemove.Duplicates.from.Sorted.Array;2 3  Public classRemoveDuplicatesfromSortedArray1 {4  Public intRemoveDuplicates (int[] A) {5     intlen=a.length;6     if(len<=1)returnLen;7     intFirst=0;8     intSecond=1;9      while(second<Len) {Ten         if(a[first]==A[second]) { Onesecond++; A}Else{ -first++; -a[first]=A[second]; thesecond++; -         } -          -       } +     returnFirst+1; -      } +      Public Static voidMain (String args[]) { ARemoveDuplicatesfromSortedArray1 service=NewRemoveDuplicatesfromSortedArray1 (); at         int[]a={1,1,1,1,2,3,3}; -         intA=service.removeduplicates (A); -      - System.out.println (a); -          -     } in}

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