/**
* 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.
* 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] .
*/
// Remove Duplicates from Sorted Array
// 时间复杂度O(n),空间复杂度O(1)
public class RemoveDuplicatesFromSortedArray {
public static int removeDuplicates(int[] arr) {
if(null == arr || arr.length == 0) {
return 0;
}
int index = 1;
for(int i=1; i<arr.length; i++) {
if(arr[i] != arr[index-1]) {
arr[index++] = arr[i];
}
}
return index;
}
public static void main(String[] arrys) {
System.out.println("A is [1,2,2,3,4,5]");
int[] arr = {1,2,2,3,4,5};
int index = removeDuplicates(arr);
System.out.println(" length = " + index);
System.out.print(" A is now:[");
for(int i=0; i<index; i++) {
System.out.print(arr[i] + " ");
}
System.out.print("]");
}
}
Remove Duplicates from Sorted Array( 滤除数组里重复的值)
最新推荐文章于 2021-06-28 21:04:04 发布