问题描述:
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.
Example:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.
分析:
要做到原地删除重复元素,非重复的元素依次排列在数组的开始,需要依次找到不重复的元素放在对应的位置上。为了记录不重复元素的位置,新建一个变量N=0,每当有一个非重复元素,N加一并将找到的元素赋值给当前N所在位置。最后返回++N
代码如下:
public int removeDuplicates(int[] nums) {
int N = 0;
for(int i=0; i<nums.length-1;){
int j=i+1;
while(nums[j]==nums[i]) {
if(j == nums.length-1) return ++N;
else j++;
}
nums[++N] = nums[j];
i = j;
}
return ++N;
}
官方答案
看了官方给的答案,比较简洁,用了两个指针,一个慢指针i,一个快指针j。当nums[j]和nums[i]相等时,增加j以跳过重复的元素,直到遇到不重复的元素,将j对应的值赋给nums[i+1],然后将i加一。一直重复上述过程直到j到达数组的最后。
代码如下:
public int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[j] != nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
不过,我的运行时间比官方给的代码的运行时间少了3ms。
网友评论