80. Remove Duplicates from Sorted Array II
题目描述:
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 in place with constant memory.
For example,
Given input array 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.
················································································································································
Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?
For example,
Given sorted array 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. It doesn’t matter what you leave beyond the new length.
题解:
给定一个排序的数组,删除重复,使每个元素最多允许重复两次,并返回新的长度。
不开另外的数组,使得原数组前几位(new length)即为去重后结果。
已知若原数组长度大于2,初始length=2,且已经确定0,1位置值一定正确。
设length-2位置的值为参考值flag,
只需从未定部分找到第一个与flag值不同的元素,即为nums[length]的值。
solution1:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.size() <= 2) {
return nums.size();
}
int length = 2;
/* 允许重复最多两次 */
/* 从length-2(=0)位置开始,比较与i(=2)位置的值是否相等:
不等:此位置值正确,length++, i++(同时更新)
相等:此位置值多余,不增加长度,仅i++,
*/
for (int i = 2; i < nums.size(); i++) {
int flag = nums[length-2];
if (flag != nums[i] ) {
nums[length] = nums[i];
length++;
}
}
return length;
}
};
本文解决LeetCode上的经典问题——删除排序数组中的重复项,使其每个元素最多出现两次,并返回新长度。文章提供了一种有效的解决方案,利用原地操作实现目标,无需额外分配空间。

1042

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



