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]
.
Solution:
public int removeDuplicates(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int size = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != nums[size]) {
nums[++size] = nums[i];
}
}
return size + 1;
}
思路:
在原数组基础上操作,数组内存空间无法减小(length),但长度指示值可以减小(size)。
有序数组依次比较,把不同值的数向前移动,同值则跳过。