Leetcode OJ 26. 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 nums = [1,1,2] ,

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

Subscribe to see which companies asked this question

Ideas

For example [1,1,1,2,2,2,3,4,5], my idea is to find the length of the repeating number in each section and then move the back number forward until the end of the array is traversed.

In the example above, we found that 1 repetitions occurred 3 times from the beginning, so we moved the number after 1 forward by 2, into [1,2,2,2,3,4,5], and then changed the Len of the array to len-2, repeating the above results until the end, the code is as follows:

1  Public classSolution {2      Public intRemoveDuplicates (int[] nums) {3         if(nums==NULL|| nums.length==0)return0;4         intLen =nums.length;5         intDuplen = 0;6          for(inti = 0; i < len-1; i++){7Duplen = 0;8              for(intj = i + 1; J < Len; J + +){9                 if(Nums[j] = = Nums[i]) duplen++;Ten                 Else  Break; One             } A             if(Duplen > 0){ -                  for(intK = i + Duplen + 1; K < Len; k++){ -Nums[k-duplen] =Nums[k]; the                 } -Len = Len-Duplen; -             } -         } +         returnLen; -     } +}

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