remove-duplicates-from-sorted-array

来源:互联网 发布:贪心算法 多机调度 编辑:程序博客网 时间:2024/05/17 03:05
packagecom.ytx.array;
/** 题目:remove-duplicates-from-sorted-array
 *
 *     描述: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].
             
 *@authoryuantian xin
 *
 *  给你一个有序数组,返回去除重复元素后数组的长度。不允许申请新的空间。
 *  思路:
 * 
 */
publicclass Remove_duplicates_from_sorted_array {
       
       publicintremoveDuplicates(int[]A) {
             
             intlen = A.length;
             if(len== 0 || A == null  ) return0;
       
       int index = 1;
       for (inti = 1; i < len; ++i) {
           if (A[i] ==A[i- 1]) {
               continue;
            }
           A[index++] =A[i];
        }
       returnindex;
    }
       publicstatic void main(String[]args) {
             /*int[] A = {1,2,2,3,3,4,4,5,6,7,9,9};*/
             intA[] = {1};
             System.out.println(newRemove_duplicates_from_sorted_array().removeDuplicates(A));
             
             for(inti = 0; i < A.length;i++) {
                    System.out.print(A[i]);
             }
             
       }
}
原创粉丝点击