leetcode-array: Remove duplicates from Sorted array

Source: Internet
Author: User

Remove duplicates from Sorted array: Removes duplicate elements from the array that is arranged

To investigate the basic operation of an array:

classSolution { Public intRemoveDuplicates (int[] nums) {        if(nums==NULL|| Nums.length==0)            return0; intindex = 1;  for(inti = 1; i<nums.length; i++){            if(nums[i]!=nums[i-1]) {Nums[index]=Nums[i]; Index++; }        }        returnindex; }     Public Static voidMain (string[] args) {int[] arr = {1, 2, 2, 3, 3 }; Arr=removeduplicates (arr); System.out.println (Arr.length);}}
Remove duplicates from Sorted Array II (Java)

For example, given sorted array A = [1,1,1,2,2,3], your function should return length = 5, and A are now [1,1,2,2,3].

Allows up to two duplicates, resulting in an array of output results.

Solution 1: When the counter is 2 o'clock, you can skip directly, otherwise the number of occurrences of the element is not super, continue to put into the result array, if new elements encountered reset counter. The overall algorithm only needs to scan the array once, so the time is O (n), the space only need to maintain an index and counter, so is O (1).

 Public intRemoveDuplicates (int[] A) {if(a==NULL|| A.length==0)        return0; intIDX = 0; intCount = 0;  for(inti=1;i<a.length;i++)    {        if(a[i]==a[i-1]) {count++; if(count>=3)                Continue; }        Else{Count= 1; } a[idx++]=A[i]; }    returnidx;}

Solution Two:

 Public classSolution { Public intRemoveDuplicates (int[] A) {if(A.length <= 2)            returna.length; intprev = 1;//Point to previous        intCurr = 2;// Point-to-current          while(Curr <a.length) {if(A[curr] = = A[prev] && A[curr] = = A[prev-1]) {Curr++; } Else{prev++; A[prev]=A[curr]; Curr++; }        }         returnPrev + 1; }}

leetcode-array: 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.