[LeetCode]100. Remove Duplicates from Sorted Array II排序数组去重
2015-12-08 19:05
369 查看
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums =
Your function should return length =
Subscribe to see which companies asked this question
解法:同排序数组去重I,本题的一个额外要求是元素最多可以重复两次。因此需要增加一个计数值,记录当前数字出现次数,计数值cnt初始化为1。同时设置一个索引idx初始化为1,记录下一个保留元素应该保存的位置。从数组的第二个元素开始扫描。如果当前元素和前一个元素相同,则++cnt,此时如果cnt>2了,则跳过这个重复值;如果小于2,则nums[idx++]=nums[i];如果当前元素和前一个元素不相同,则重置cnt=1,且保留下当前元素nums[idx++]=nums[i]。
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,
2and
3. It doesn't matter what you leave beyond the new length.
Subscribe to see which companies asked this question
解法:同排序数组去重I,本题的一个额外要求是元素最多可以重复两次。因此需要增加一个计数值,记录当前数字出现次数,计数值cnt初始化为1。同时设置一个索引idx初始化为1,记录下一个保留元素应该保存的位置。从数组的第二个元素开始扫描。如果当前元素和前一个元素相同,则++cnt,此时如果cnt>2了,则跳过这个重复值;如果小于2,则nums[idx++]=nums[i];如果当前元素和前一个元素不相同,则重置cnt=1,且保留下当前元素nums[idx++]=nums[i]。
class Solution { public: int removeDuplicates(vector<int>& nums) { if (nums.size() < 3) return nums.size(); int idx = 1, cnt = 1; for (int i = 1; i < nums.size(); ++i) { if (nums[i - 1] == nums[i]) { ++cnt; if (cnt <= 2) nums[idx++] = nums[i]; } else { nums[idx++] = nums[i]; cnt = 1; } } return idx; } };
相关文章推荐
- 关于傅里叶分析与香农采样定理
- maven安装 JDK问题
- leetcode - Binary Tree Level Order Traversal II
- Spring的核心技术(七)---循环依赖
- 基于Wolf32F031 自由评估板的Accelerometer(MMA7455)实验硬件原理及软件API使用方法(适用于STM32F030/031)
- 抽象工厂
- python PIL 处理图片的模快 Image类
- 转载:tomcat过程原理
- iOS 【原生API 缓存类NSCache】
- Spring的核心技术(六)---基于Setter的依赖注入
- sql 存储过程 分页
- spring 动态定时任务
- 基于Wolf32F031 自由评估板的IIC EEPROM实验硬件原理及软件API使用方法(适用于STM32F030/031)
- Java&Xml教程(二)使用DOM方式解析XML文件
- Java&Xml教程(二)使用DOM方式解析XML文件
- Java&Xml教程(二)使用DOM方式解析XML文件
- guava处理字符串与List之间,字符串与map之间的转换<转>
- UITextView 如何使显示不全的单词不折行显示
- android adb 卸载内置系统apk方法
- Android 操作SQLite基本用法