[LeetCode]Remove Duplicates from Sorted Array II
来源:互联网 发布:iphone视频截图软件 编辑:程序博客网 时间:2024/06/07 02:19
题目描述:给出一列有序数组,最多可以保留两个相同元素,如果还有更多次重复的话,那么要删除重复的元素,并且要求返回元素个数。
比如说,[1,1,1,2,2,3]最后要输出5,[1,1,2,2,3]
解题思路:Two Pointers。两个指针一前一后,相对上一题,增加一个times(控制元素出现个数)的变量,初始化为一次。因为任何一个出现的元素最少出现一次,少于一次它就是不出现了_(:з」∠)_
==============================================================================================================
综上而述,代码如下:一次AC.
class Solution {public: int removeDuplicates(vector<int>& nums) { int N = nums.size(); if ( N<=2 ) return N; vector<int>::iterator iter=nums.begin(); vector<int>::iterator iter1=iter+1; int times=1; while( iter1 != nums.end() ) { if( *iter==*iter1 ) { ++times; if(times==2) iter1++; if(times>2) nums.erase(iter1); } else { if( times==1 ) ++iter; if( times>=2 ) iter+=2; ++iter1; times=1; } } return N=nums.size(); }};
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
- OC简单小功能的实现-利用三个代表三原色的滑块控制背景颜色变化
- POJ1006 Biorhythms
- String、StringBuffer与StringBuilder之间区别
- 3620 Avoid The Lakes【dfs】
- Java可视化计算器
- [LeetCode]Remove Duplicates from Sorted Array II
- 精通Hibernate——建立双向一对多关联
- SDUToj2122数据结构实验之链表七:单链表中重复元素的删除
- ASP.NET C# 连接SQL SERVER数据库 实现用户注册页面
- FZU 1752 A^B mod C
- 稳定排序和不稳定排序
- GIT
- C语言编程入门——综合练习(一)
- andoid中的通知