/**
*
* @author gentleKay
* 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].
*
* 给定一个已排序的数组,将重复项移除到位,这样每个元素只出现一次,并返回新的长度。
* 不要为另一个数组分配额外的空间,必须在内存恒定的情况下就地分配。
* 例如,
* 给定输入数组a=[1,1,2],
* 您的函数应该返回length=2,而a现在是[1,2]。
*/
/** * * @author gentleKay * 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]. * * 给定一个已排序的数组,将重复项移除到位,这样每个元素只出现一次,并返回新的长度。 * 不要为另一个数组分配额外的空间,必须在内存恒定的情况下就地分配。 * 例如, * 给定输入数组a=[1,1,2], * 您的函数应该返回length=2,而a现在是[1,2]。 */ public class Main31 { public static void main(String[] args) { // TODO Auto-generated method stub int[] A = {1,1,1,2}; System.out.println(removeDuplicates(A)); } public static int removeDuplicates(int[] A) { int count = 1; for (int i=0;i<A.length-1;i++) { if (A[i] != A[i+1]) { A[count]=A[i+1]; count++; } } return count; } }