LeetCode|LeetCode 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 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
class Solution {
public:
int removeDuplicates(vector& nums) {
int n = nums.size(), skip = 0;
if(n <= 2) return n;
int cnt = 0, index = 0;
for(int i = 0;
i 0 && nums[i] == nums[i-1]){
cnt++;
if(cnt >= 3)
continue;
}
else cnt = 1;
nums[index++] = nums[i];
}
return index;
}
};
【LeetCode|LeetCode Remove Duplicates from Sorted Array II】用了index指明了结果数组中每个地方的正确数字,不必每次遇到重复数字时全局移动几乎整个后面的数组,用cnt变量表明到底出现了几次。
推荐阅读
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- leetcode|leetcode 92. 反转链表 II
- 二叉树路径节点关键值和等于目标值(LeetCode--112&LeetCode--113)
- LeetCode算法题-11.|LeetCode算法题-11. 盛最多水的容器(Swift)
- LeetCode(03)Longest|LeetCode(03)Longest Substring Without Repeating Characters
- Leetcode|Leetcode No.198打家劫舍
- [leetcode数组系列]1两数之和
- 数据结构和算法|LeetCode 的正确使用方式
- leetcode|今天开始记录自己的力扣之路
- LeetCode|LeetCode 876. 链表的中间结点