Given an integer array nums
sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums
. More formally, if there are k
elements after removing the duplicates, then the first k
elements of nums
should hold the final result. It does not matter what you leave beyond the first k
elements.
Return k
after placing the final result in the first k
slots of nums
.
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
给定一个按非递减顺序排序的整数数组 nums
,就地删除一些重复项,使每个唯一元素最多出现两次。元素的相对顺序应保持不变。
由于在某些语言中无法改变数组的长度,你必须将结果放在数组 nums
的前部。更具体地说,如果删除重复项后有 k
个元素,那么 nums
的前 k
个元素应该包含最终结果。超出前 k
个元素的部分不重要。
在将最终结果放置在 nums
的前 k
个槽位后,返回 k
。
不要为另一个数组分配额外空间。你必须通过就地修改输入数组并且仅使用 O(1) 的额外内存来完成此操作。
Example 1:
nums = [1,1,1,2,2,3]
5
, nums = [1,1,2,2,3,_]
k = 5
, with the first five elements of nums
being 1
, 1
, 2
, 2
and 3
respectively. It does not matter what you leave beyond the returned k
(hence they are underscores).Example 2:
nums = [0,0,1,1,1,1,2,3,3]
7
, nums = [0,0,1,1,2,3,3,_,_]
k = 7
, with the first seven elements of nums
being 0
, 0
, 1
, 1
, 2
, 3
and 3
respectively. It does not matter what you leave beyond the returned k
(hence they are underscores).Constraints:
1 <= nums.length <= 3 * 10^4
-10^4 <= nums[i] <= 10^4
nums
is sorted in non-decreasing order.代码实现了从排序数组中移除多余的重复项,确保每个元素最多出现两次。
初始化变量:
index
: 用于跟踪数组中当前非重复元素的位置的指针。cnt_index
: 用于记录当前 index
指向的元素在数组中出现的次数的计数器。遍历数组:
for
循环从数组的第二个元素(索引 1
)开始遍历。处理元素:
cnt_index < 2
(即当前 index
指向的元素出现次数少于2次)时,将当前遍历到的元素 (nums[i]
) 移动到 index + 1
的位置,并更新 cnt_index
。使用条件运算符判断是否增加 cnt_index
。cnt_index
等于2,并且当前元素与 index
指向的元素不同时,将当前元素移动到 index + 1
的位置,并将 cnt_index
重置为1。返回结果:
index + 1
作为新数组的长度,这表示新数组中元素的实际数量。nums
的长度。需要遍历一次数组来移除多余的重复项。class Solution {
public:
int removeDuplicates(vector<int>& nums) {
// 降序数组,原地移除出现次数超过2次的元素。
// 设置 cnt_index 记录当前index下标的元素出现的次数
int index = 0, cnt_index = 1;
for (int i = 1; i < nums.size(); i++) {
if (cnt_index < 2) {
nums[++index] = nums[i];
cnt_index = nums[index - 1] == nums[index] ? cnt_index + 1 : cnt_index;
} else if (nums[index] != nums[i]) {
nums[++index] = nums[i];
cnt_index = 1;
}
}
return index + 1;
}
};
优化后的代码进一步简化了移除数组中多余重复项的逻辑,确保每个元素最多出现两次。
特殊情况处理:
初始化变量:
index
: 设置为1,因为前两个元素(即索引为0和1的元素)默认保留。遍历并更新数组:
nums[i]
不等于 nums[index]
或者不等于 nums[index - 1]
,则递增 index
并更新 nums[index]
。这样确保每个元素最多只出现两次。返回结果:
index + 1
作为新数组的长度,代表去除多余重复项后的数组长度。class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.size() < 3) return nums.size();
int index = 1;
for (int i = 2; i < nums.size(); i++) {
if (nums[i] != nums[index] || nums[i] != nums[index - 1]) {
nums[++index] = nums[i];
}
}
return index + 1;
}
};