leetcode刷题,总结,记录,备忘 80
2015-12-12 23:43
387 查看
leetcode80 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 =
Your function should return length =
It doesn't matter what you leave beyond the new length.
Subscribe to see which companies asked this question
题目要求是最多保留2个相同,第三个删掉。这里我灵机一动,想了个绝妙的方法。使用2个set容器,在遍历数组的时候,根据奇偶次数,分别往2个不同的set容器里插入数值,保证每个相同的只有2个数会被成功插入,如果有第三个就会插入失败,此时删掉他,最后返回2个set容器的长度和即可。
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
set<int> s1;
set<int> s2;
for (int i = 0; i < nums.size(); ++i)
{
pair<set<int>::iterator, bool> p;
if (i % 2 == 0)
{
p = s1.insert(nums[i]);
if (p.second == false)
{
nums.erase(nums.begin() + i);
i--;
}
}
else
{
p = s2.insert(nums[i]);
if (p.second == false)
{
nums.erase(nums.begin() + i);
i--;
}
}
}
return s1.size() + s2.size();
}
};
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,
2and
3.
It doesn't matter what you leave beyond the new length.
Subscribe to see which companies asked this question
题目要求是最多保留2个相同,第三个删掉。这里我灵机一动,想了个绝妙的方法。使用2个set容器,在遍历数组的时候,根据奇偶次数,分别往2个不同的set容器里插入数值,保证每个相同的只有2个数会被成功插入,如果有第三个就会插入失败,此时删掉他,最后返回2个set容器的长度和即可。
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
set<int> s1;
set<int> s2;
for (int i = 0; i < nums.size(); ++i)
{
pair<set<int>::iterator, bool> p;
if (i % 2 == 0)
{
p = s1.insert(nums[i]);
if (p.second == false)
{
nums.erase(nums.begin() + i);
i--;
}
}
else
{
p = s2.insert(nums[i]);
if (p.second == false)
{
nums.erase(nums.begin() + i);
i--;
}
}
}
return s1.size() + s2.size();
}
};
相关文章推荐
- 【C++】JSON文件的读取和生成
- 模仿淘宝客户端倒计时控件
- 关于dip、dpi和分辨率的一些事
- python 编码与解码 decode解码 encode 编码
- ORA-06553:PLS-306:wrong number or types of arguments in call to ''
- Nginx的负载均衡 - 最少连接 (least_conn)
- hdu 5595
- SQLite Tutorial 3 : Working with important SqLite Queries (SELECT, INSERT, DELETE, UPDATE,WHERE...)
- [hdoj试题]A+B for Input-Output Practice (VII)
- Solve 0x80004005 issue, cannot access sharefolder under windows2012
- Java Notes-3
- Nginx的负载均衡 - 最少连接 (least_conn)
- POJ 1062 迪杰斯特拉
- VBS 改 IP(modify IP by VBS)
- Java Notes-1
- Java Notes-2
- java模拟异步消息机制
- RocEDU.阅读.写作《你的灯亮着吗?》
- Linux常用命令(自我总结)
- 图片的内存优化