Easy understand Java solution with comments


  • 1
    W
        //思路: 前后两根指针
        public int removeDuplicates(int[] A) {
            if(A == null || A.length == 0) 
                return 0;
            int index = 1;  //index代表下一个要存储的下标
            for(int j = 1; j < A.length; j++) { //从下标1开始遍历数组
                if(A[j] != A[index-1]) {    //当前元素与有效数组的最后一位不等,则纳入
                    A[index] = A[j];    //加入到有效数组中
                    index++;    //长度加1
                }
            }
            return index;
        }

  • 0
    C

    @WuQiFu said in Easy understand Java solution with comments:

        //思路: 前后两根指针
        public int removeDuplicates(int[] A) {
            if(A == null || A.length == 0) 
                return 0;
            int index = 1;  //index代表下一个要存储的下标
            for(int j = 1; j < A.length; j++) { //从下标1开始遍历数组
                if(A[j] != A[index-1]) {    //当前元素与有效数组的最后一位不等,则纳入
                    A[index] = A[j];    //加入到有效数组中
                    index++;    //长度加1
                }
            }
            return index;
        }

Log in to reply
 

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