首页 > 代码库 > LeetCode80 Remove Duplicates from Sorted Array II

LeetCode80 Remove Duplicates from Sorted Array II

题目:

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice? (Medium)

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 I 中的双指针思路,只不过增加一个变量count记录出现的次数,两次以内的仍然可以添加的数组中。

代码:

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

 

 

LeetCode80 Remove Duplicates from Sorted Array II