"Lintcode" deletes duplicate numbers in a sorted array

Source: Internet
Author: User
Tags lintcode
Delete a repeating number in a sorted array
Describe: given a sorted array, delete the recurring number in the original array so that each element appears only once, and the length of the new array is returned.

Do not use additional array space, you must be in situ without extra space to complete the condition. Examples

To the array a =[1,1,2], your function should return a length of 2, at this time a=[1,2].


Idea: Because you don't want to use extra array space, you can only move from the original array. You can index with a variable with an initial value of 0 (the subscript of the first element is recorded). Scans one by one, when an element that is not logged, an index value of +1, and changes the element value that the array is subscript to the index value to the current element.

In short, it means that the elements that will appear are saved from the beginning of the array, and you do not need to return the original array.

The code is as follows:

public class Solution {
    /**
     * @param a:a array of integers
     * @return: Return an integer
     *
    * T RemoveDuplicates (int[] nums) {
        //write your code here
        if (nums.length = 0)
        {return
            0;
        }
        else if (nums.length = = 1)
        {return
            1;
        }
        
        int ipos = 0;
        
        for (int i = 1;i < nums.length;i++)
        {
            if (Nums[i]!= Nums[ipos])
            {
                Nums[++ipos] = nums[i]; 
            }
        }
        
        Return ipos+1
    }
}


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.