In JAVA, the length of an array cannot be changed!There may be a bug here.

  • 0

    Please don't laugh at my naive codes...They are just written in a hurry. I think it is not suitable to use int[] here, since the last few elements of A are ignored!

    public class Solution {
    public int removeDuplicates(int[] A) {
        TreeSet<Integer> trst = new TreeSet<Integer> ();
        for(int i=0; i < A.length; i++) {
        Iterator<Integer> it =trst.iterator();
        int i = 0;
        while(it.hasNext()) {
        // for(int j=i; i < A.length; i++) {
        //     A[j]=Integer.MAX_VALUE;
        // }
        return i;


  • 1

    Problem description says

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

    It means only the length of new array is needed. It doesn't mean the original array need to be change.

  • 0

    It also says that A = [1,1,2] should afterwards be A=[1,2]. Therefor you should change the array size which is not possible on an array in Java.
    Since you should not create a new Array Instance what is the correct solution to this? Using an ArrayList to remove Items and convert back to an int[] returns a new Array as well.

  • 0

    I've solved it like this:

    public int removeDuplicates(int[] A) {
        if(A.length == 0) {
            return 0;
        int length = A.length;
        for(int i = 0; i < length; i++) {
            Boolean found = false;
            for(int j = 0; j < length; j++) {
                if(A[i] == A[j]) {
                    if(found) {
                        int k = length - j - 1;
                        System.arraycopy(((Object) (A)), j + 1, ((Object) (A)), j, k);
                    } else {
                        found = true;
                } else if(A[j] > A[i]) {
        return length;

    this returns an array like {1,2,3,4,5,6,7,7,7,7,7,7,7} with 7 filling the space which is no longer needed. The Problem description

    Given input array A = [1,1,2], Your function should return length = 2, and A is now [1,2].

    is a little missleading imo.

  • 0

    If you did not change the array:
    here is what you will get:
    Input: [1,1,2]
    Output: [1,1]
    Expected: [1,2]

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.