首页 > 代码库 > 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 1
, 1
, 2
, 2
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。