问题描述:
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;
}
}

本文介绍了一个不使用额外空间,仅通过修改输入数组来去除重复元素的算法。该算法利用双指针技巧,确保每个元素只出现一次,并返回新数组的有效长度。
1106

被折叠的 条评论
为什么被折叠?



