题目:
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.
题意:
本题是Remove Duplicates的延伸题。目标是将输入的排序整型数组中重复次数超过3次的元素去掉。如:[1, 1, 1, 2, 2, 3]的输出为数组长度5,即变形为[1, 1, 2, 2, 3]。
解题思路:
刚开始以为只是简单地计数去掉非法元素后的长度,只需对出现重复的情况进行计数,若重复次数超过3,则不计入数组长度统计。提交之后,WA... 所以知道为啥这题的踩那么多== 因为不仅要求输出去重后的长度,还要将输入nums修改为去重后的形式。
解法一:
新建一个数组,合法元素直接插入数组尾,最终将nums重新赋值为新数组。缺点是需开辟新的数组空间。
代码:
int removeDuplicates(vector<int>& nums) {
if(nums.size() < 1)
return 0;
int length = nums.size(), count = 0, cur_count = 0;
vector<int> new_nums;
for(int i = 0; i < length; i++)
{
if(i > 0 && nums[i] == nums[i-1])
cur_count++;
else
cur_count = 0;
if(cur_count < 2)
{
new_nums.insert(new_nums.end(), nums[i]);
count++;
}
}
nums = new_nums;
return count;
}
解法二:
使用erase,在原数组上直接删除重复元素。难点在于使用iterator遍历数组。
代码:
int removeDuplicates(vector<int>& nums) {
if(nums.size() < 1)
return 0;
int count = 0, cur_count = 0, before = nums[0];
for(vector<int>::iterator it = nums.begin(); it != nums.end();)
{
if(it != nums.begin() && *it == before)
cur_count++;
else
{
cur_count = 0;
before = *it;
}
if(cur_count < 2)
{
count++;
it++;
}
else
it = nums.erase(it);
}
return count;
}
意外的是两种解法并没有本质上的效率差异==
题外话:哈哈哈哈!狗年大吉!新的一年,愿自己做好自己可做的事情,管理好自己。愿自己可以顺遂面对一切。愿家人朋友健康快乐!
Listening to 'Turning' ~