题目: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.
解答:
class Solution {
public: int removeDuplicates(vector<int>& nums) { int size = nums.size(); if(size <= 2) return size; int cur_index = 0; int p = 1; int q = 2; while(q < size) { if(nums[cur_index] != nums[p]) { nums[++cur_index] = nums[p++]; q = p + 1; } else { if(nums[p] != nums[q]) { nums[++cur_index] = nums[p++]; q = p + 1; } else { p++; q = p + 1; } } } nums[++cur_index] = nums[p++]; return cur_index + 1; }};
其中,cur_index一直控制着最终应该返回的只允许两次重复的边界,而p是当前正在判断的数字,q为其下一个数字。
自己的题解过程,看起来很复杂,其实,仔细一想,只需要一个变量记录当前的位置,需要一个变量来迭代的往后走,判断该变量指向的位置的前两个位置是否与迭代变量所指向的相同。
优秀答案:
class Solution {
public: int removeDuplicates(vector<int>& nums) { int size = nums.size(); if(size <= 2) return size; int index = 2; for(int i = 2;i < size;i++) { if(nums[index - 2] != nums[i]) { nums[index++] = nums[i]; } } return index; }};