80. Remove Duplicates from Sorted Array II
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.
解题思路:由于每个元素至多出现两次,所以只需要判断nums[i]是否等于nums[i-2],如果是说明该数字出现的次数超过了2次,否则,该数字出现的次数少于2次,将它加到结果数组中。
class Solution { public: int removeDuplicates(vector<int>& nums) { int i=0; for(int num: nums){ if(i<2||num>nums[i-2]) nums[i++]=num; } return i; } };