[Leetcode] Remove Duplicates from Sorted Array II
来源:互联网 发布:广东广电网络营业厅 编辑:程序博客网 时间:2024/04/30 17:18
描述
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 的升级版,增加了一个条件是每个值最多可以出现两次。
和原来的意思一致,使用双指针的方法遍历数组,当满足下面两种情况之一时,将当前的值储存到新数组中。
1. 当前值与新数组最后一个值不同;
2. 当前值与新数组最后一个值相同,但这个值在新数组中只出现了一次。
代码
class Solution {public: int removeDuplicates(vector<int>& nums) { if (nums.size() <= 2) return nums.size(); int i = 1, j = 2; while (j < nums.size()) { if ((nums[j] > nums[i]) || ((nums[j] == nums[i]) && nums[i] != nums[i - 1])) nums[++i] = nums[j]; j++; } return i + 1; }};
相关问题
Remove Duplicates from Sorted Array
0 0
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array II
- LeetCode-Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- LeetCode - Remove Duplicates from Sorted Array II
- LeetCode:Remove Duplicates from Sorted Array II
- LeetCode | Remove Duplicates from Sorted Array II
- Leetcode: Remove Duplicates from Sorted Array II
- 【leetcode】Remove Duplicates from Sorted Array II
- Leetcode: Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- Leetcode Remove Duplicates from Sorted Array II
- AndridStudio错误TransformException分析和解决
- 常见防网站数据采集策略方法和它的弊端及采集对策
- 深度学习优化方法比较
- 欢迎使用CSDN-markdown编辑器
- [51nod1169]石子游戏
- [Leetcode] Remove Duplicates from Sorted Array II
- Gvim各个模式下面的快捷键
- LeetCode 142. Linked List Cycle II
- 401. [LeetCode]Binary Watch
- EvnetBus消息传递 优化写法较传统写法更好理解、使用
- LeetCode 137. Single Number II
- Android新手,xxx has stopped。希望有人帮我看一下日志提示的错误我应该去改哪。
- 一个新的Http请求库
- 《时代周刊》2016年度25项最佳发明出炉