Remove Duplicates from Sorted Array, Leetcode 解题笔记

Given a sorted array, remove the duplicates in place such that each element appear only once and 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 should return length = 2, and A is now [1,2].

这道题很简单直接,不过有歧义,array的size是不可改变的,所以题目要求改变array A是不可能的,最多就把array整体向左shift把重复的元素都覆盖掉。

public class Solution {
    public int removeDuplicates(int[] A) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int i = 0;
        int j;
        if(A.length <= 1) return A.length;
        for(j = 1; j < A.length; j++){
            if(A[i] != A[j]){
                A[++i] = A[j];
        return i+1;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s