LeetCode解题 80:Remove Duplicates from Sorted Array II
Problem 80: Remove Duplicates from Sorted Array II [Medium]
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.
Example 1:
Given nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It doesn’t matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,1,2,3,3],
Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.
It doesn’t matter what values are set beyond the returned length.
来源:LeetCode
解题思路
与题解26:Remove Duplicates from Sorted Array类似,只是要把重复的频率上限改为2。
具体思路:
- 使用一个指针
index
指向需要修改的位置,nums[0]
~nums[index-1]
代表已经检测过的未重复2次以上的数字。 - 遍历数组,用
last
记录上一个数值的下标,跳过重复次数大于2的数字(即nums[i] == nums[last] && i - last > 1
),将符合要求的数字填入nums[index]
,指针index
向后移一位。 - 数组个数小于3时直接返回。
时间复杂度 O ( n ) O(n) O(n),空间复杂度 O ( 1 ) O(1) O(1)。
运行结果:
要点:双指针
Solution (Java)
class Solution {
public int removeDuplicates(int[] nums) {
int N = nums.length;
if(N < 3) return N;
int index = 1;
int last = 0;
for(int i = 1; i < N; i++){
while(i < N && nums[i] == nums[last]){
if(i - last < 2){
nums[index++] = nums[i];
}
i++;
}
if(i < N){
last = i;
nums[index++] = nums[i];
}
}
return index;
}
}