Remove Duplicates from Sorted Array

Source: Internet
Author: User

Given a sorted array nums, remove the duplicates in-place such that all element appear only once and re Turn the new length.

Do not allocate extra space for another array, you must does this by modifying the input array in-place with O (1) Extra memo Ry.

Example 1:

Nums Nums being 1 and 2 respectively. It doesn ' t matter what do you leave beyond the returned length.

Example 2:

Nums nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn ' t matter what values is set beyond the returned length.

Clarification:

Confused why the returned value is a integer but your answer are an array?

Note that the input array was passed in by reference, which means modification to the input array would be known to the call ER as well.

Internally can think of this:

Nums is passed on by reference. (i.e., without making a copy) int len = RemoveDuplicates (nums);//any modification to nums in your function would is known By the caller.//using the length returned by your function, it prints the first Len elements.for (int i = 0; i < Len; i++) {print (nums[i]);}
//pointer:time:o (n), Space:o (1)   Public intRemoveDuplicates (int[] nums) {        if(Nums = =NULL) {            return0; }                inti = 0;//record the last non-repeating position that is the current position                 for(intj = 0; J < Nums.length; J + +) {            if(nums[j]! = Nums[i]) {nums[++i] =Nums[j]; }        }                returni + 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.