Leetcode -- remove duplicates from sorted Array

Source: Internet
Author: User

Given a sorted array, remove the duplicates in place such that each element appear onlyOnceAnd return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array A =[1,1,2],

Your function shocould return length =2, And a is now[1,2]

Problem:

Remove the repeated values in the given array and return the length of the array after deduplication. Note that the problem requires that another array cannot be defined, so the results are saved in the input array.

Ideas:

Compare the records from the first to the second. If the values are not the same, they are saved to A. If the values are equal, they are moved back until the results are saved every time they are found. Finally, the length of the index record of the New Result array is used.

For example, array [,]

First, compare and define result = 1. A [result ++] is used to save the result array.

1! = 2 so a [Result] is a [1], so a [1] = 2, and another result ++ is followed by result = 2;

2 = 2 so do not save, continue backward loop comparison.

2! = 3 so a [Result] is a [2], so a [2] = 3, and result = 3 after result ++'

.......

The loop ends until the end. result is the new array length, and a is the deduplicated array.

public class Solution {    public int removeDuplicates(int[] A) {        int length = A.length;        int result = 1;        if(length<=1)            return length;        else{            for(int i=0;i<length-1;i++){                if(A[i]!=A[i+1]){                    A[result++]=A[i+1];                    }                }            }        return result;    }}

 

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.