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.
Subscribe to see which companies asked this question
class Solution { public: int removeDuplicates(vector<int>& nums) { if (nums.size() < 3) return nums.size(); int idx = 1, cnt = 1; for (int i = 1; i < nums.size(); ++i) { if (nums[i - 1] == nums[i]) { ++cnt; if (cnt <= 2) nums[idx++] = nums[i]; } else { nums[idx++] = nums[i]; cnt = 1; } } return idx; } };
[LeetCode]100. Remove Duplicates from Sorted Array II排序数组去重
原文:http://www.cnblogs.com/aprilcheny/p/5030671.html