LeetCode:Remove Duplicates from Sorted Array II

Problems:

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 from sorted Array的基础上加入计数count用来判断重复的次数

 1 class Solution {
 2 public:
 3     int removeDuplicates(vector<int>& nums) {
 4         if(nums.size()==0) return 0;
 5         
 6         int index=0;
 7         int count=1;
 8         for(int i=1;i<nums.size();i++)
 9         {
10            if(nums[index]!=nums[i])
11            {
12                nums[++index]=nums[i];
13                count=1;
14             }
15            else if(nums[index]==nums[i]&&count<=1)
16            {
17                 nums[++index]=nums[i];
18                 count++;
19             }
20         
21         }
22         return index+1;
23         
24     }
25 };

解法二:

代码简洁聪明

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        
        if(nums.size()<=2)  return n;
        
        int index=2;
        for(int i=2;i<nums.size();i++)
        {
                if(nums[i]!=nums[index-2])
                   nums[index++]=nums[i];
         }
                
          return index;      
               
    }
};
原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4551109.html