美文网首页
Remove Duplicates

Remove Duplicates

作者: 夏的背影 | 来源:发表于2017-03-28 19:06 被阅读12次

question:

//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].

answer:

public class removeDuplicates {

    public static int removeDuplicates(int[] array){
        int j= 0;
        for(int i = 1;i<array.length;i++){
            if (array[j]!=array[i]){
                ++j;
                array[j]=array[i];
            }
        }
        return j+1;
    }

    public static void main(String[] args) {
        int[] array1 = {1,1,2,3,3,4,5,6,6,10,10};
        int length = removeDuplicates(array1);
        for (int i=0;i<length;i++){
            System.out.println(array1[i]);
        }
        System.out.println("the array length is "+length);
    }

}

相关文章

网友评论

      本文标题:Remove Duplicates

      本文链接:https://www.haomeiwen.com/subject/zbcsottx.html