[LeetCode]Remove Duplicates from Sorted Array II

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 1122 and 3. It doesn't matter what you leave beyond the new length.

 和Remove Duplicates from Sorted Array一个道理,唯一的区别就是需要判断最近的两个值是否相同。

 1 class Solution {
 2 public:
 3     int removeDuplicates(vector<int>& nums) {
 4         if(nums.size()<=2) return nums.size(); 
 5         int result=1;
 6         for(int i=2;i<nums.size();i++)
 7         {
 8             if((nums[i]!=nums[result])||(nums[i]==nums[result] && nums[result]!=nums[result-1]))
 9             {
10                 result++;
11                 nums[result] = nums[i];
12             }
13         }
14         return (result+1);
15     }
16 };
原文地址:https://www.cnblogs.com/Sean-le/p/4813674.html