问题描述:
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 by modifying the input array in-place with O(1) extra memory.
思路:
因为不能使用额外空间,所以使用双指针,一个个向后搜索并排列。len代表目前的长度,i去进行一个个的搜索。
代码:
class Solution {
public int removeDuplicates(int[] nums) {
if(nums == null) return 0;
int len = 1;
for(int i = 1; i < nums.length; i++){
if(nums[i] != nums[i-1]){
if(nums[i] != nums[len])
nums[len] = nums[i];
len++;
}
}
return len;
}
}