leetcode80 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.

 1 class Solution {
 2 public:
 3     int removeDuplicates(vector<int>& nums) {
 4         int ans=0;
 5         int size=nums.size();
 6         if(size==0)
 7             return 0;
 8         int p=0;
 9         
10         ans++;
11         p++;
12         int two_flag=1;
13         int cur=nums[0];
14         for(int i=1;i<size;i++)
15         {
16             if(nums[i]==cur)
17             {
18                 if(two_flag!=2)
19                 {
20                     two_flag++;
21                     ans++;
22                     if(i!=p)
23                     {
24                         nums[p]=nums[i];
25                     }
26                     p++;
27                 }
28             }
29             else
30             {
31                 two_flag=1;
32                 ans++;
33                 cur=nums[i];
34                 if(i!=p)
35                 {
36                     nums[p]=nums[i];
37                 }
38                 p++;
39             }
40         }
41         return ans;
42     }
43 };
View Code
原文地址:https://www.cnblogs.com/jsir2016bky/p/5105971.html