Remove Duplicates from Sorted Array II
来源:互联网 发布:淘宝店铺旺旺在哪里 编辑:程序博客网 时间:2024/06/05 19:53
一、问题描述
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.
二、思路
去除数组中重复数大于2的元素,并将数组最后长度返回。
最关键的地方在于判断多余的变量flag,由于是有序数组,当下一个元素和当前元素不同时,flag变量重新赋值为0。还有vector的erase函数必须要注意参数类型是string::iterator的类型,而且删除元素后指向下一个元素,所以我们用--i将指针回到原位置。
三、代码
class Solution {public: int removeDuplicates(vector<int>& nums) { int n = nums.size(); int flag = 0; for(int i = 1; i < n; ++i){ if(nums[i] == nums[i - 1]){ flag++; if(flag > 1){ --n; nums.erase(nums.begin() + i); --i; } }else{ flag = 0; } } return n; }};
0 0
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- Remove duplicates from sorted array II
- Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array II
- LeetCode-Remove Duplicates from Sorted Array II
- 【IOS学习】http异步文件上传和下载以及进度指示
- scanf的特殊用法 const用法、数值型数-字符串转换、可变长参数
- 动态规划----Minimum Path Sum
- 上传 与下载
- 关于获取当前时间有时差的问题
- Remove Duplicates from Sorted Array II
- HTML 表单制作
- CSS3 text-overflow 属性
- 数据结构实验之查找五:平方之哈希表
- View的事件体系
- SpringMVC访问静态资源的三种方式
- UVAlive 6800 The Mountain of Gold?(负环判断)
- 面对对象和面向过程
- linux shell awk获得外部变量(变量传值)简介