Remove Duplicates from Sorted Array II
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice 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.
Clarification:
Confused why the returned value is an integer, but your answer is an array?
Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller.
Internally you can think of this:
//nums is passed in by reference. (i.e, without making a copy)
int len = removeDuplicates(nums);
//any modification to nums in your function would be known by the caller.
//using the length returned by your function, it prints the first len elements.
for(int i = 0; i < len; i++) {
print(nums[i]);
}
今天的题目是去除有序数组中的重复元素,不过这次不是一个元素只能出现一次了,相同的元素最多可以出现两次。而且,本题还要求在输入数组上进行操作,不能占用额外的内存空间,要求最后返回保留的数组的长度n,且输入数组的前n项要正好是我们最后保留的元素。
对于这道题,我们可以维护两个指针(或者说索引),快指针指向我们当前判断的元素,慢指针指向我们保留的最后一个元素的索引+1,即慢指针正好是最终题目要求的结果——保留的数组的长度,当我们判定快指针指向的元素重复的次数没有超过2时,就将快指针所指的元素赋值给慢指针所指向的位置,同时慢指针++,否则慢指针不动,快指针继续向后遍历。
当然,我们还要考虑到一些特殊的情况。当输入数组的长度小于等于2时, 元素一定不会出现重复,所以直接返回原数组即可。而且,当数组长度大于2时,数组的前2个元素也是一定会被保留下来的,所以我们定义的两个指针只需从2开始判断。
实现的代码如下:
public class Solution {
public int removeDuplicates(int[] nums) {
int len = nums.length;
if(len <= 2) { //如果数组长度小于等于2,则无论如何都不需要去重,直接返回即可
return len;
}
int slow = 2, fast = 2; //定义两个指针,一个快指针一个慢指针,快指针表示当前检查到的元素的索引,慢指针表示被保留的最后一个元素的索引
while(fast < len) {
if(nums[slow-2] != nums[fast]) { //由于相同元素最多出现两次,因此需要判断当前元素与上上一个保留的元素是否相等
nums[slow] = nums[fast];
slow++;
}
fast++;
}
return slow;
}
}
完美解决问题,今日每日一题结束。