【LeetCode】080. Remove Duplicates from Sorted Array II
2024-10-21 05:36:17
题目:
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.
题解:
Solution 1
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int k = ;
int n = nums.size();
if(n < )
return n;
int index = , cnt = ;
for(int i = ; i < n; ++i){
if(nums[i] != nums[index]){
cnt = ;
nums[++index] = nums[i];
} else if(++cnt <= k){
nums[++index] = nums[i];
}
}
return index + ;
}
};
Solution 2
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int k = ;
int n = nums.size();
if(n < k)
return n;
int index = k;
for(int i = k; i < n; ++i){
if(nums[i] != nums[index - k])
nums[index++] = nums[i];
}
return index;
}
};
此解与Remove Duplicates from Sorted Array相似
最新文章
- MergeRecord_C++中map的使用
- chrome浏览器渲染白屏问题剖析
- 跨域http请求
- CEF3开发者系列之进程间消息传递
- [poj3321]Apple Tree(dfs序+树状数组)
- 英語版Windows Server 2012 R2を日本語化する手順
- android studio问题-ICCP:Not recognizing known sRGB profile
- SuperGridControl 使用小技巧
- lucene、lucene.NET详细使用与优化详解
- N对括号的合法组合
- Oracle数据库之视图与索引
- UItableViewCell上的button点击无响应的办法
- PAT (Advanced Level) 1107. Social Clusters (30)
- GIt -- git push 远程分支老是需要重新输入公钥密码问题处理?
- Difference Between Git and SVN
- 安装redis及异常处理
- S 实现精确加减乘除
- HTTP 总结
- 【Java】 剑指offer(7) 二叉树的下一个结点
- QTextCodec 类