80. Remove Duplicates from Sorted Array II
来源:互联网 发布:电子取证软件 编辑:程序博客网 时间:2024/06/16 22:52
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.
思路:因为是排好序的数组,所以统计每个数字出现的次数,下标idx表示重新给nums数组赋值的下标,超过两次的赋值两次。小于两次的就直接赋值,更新idx和now。注意全部相同的情况(1,1,1,1),扫完数组才执行Count
class Solution {public: void Count(vector<int>& nums, int cnt, int& idx, int now){ if(cnt >= 2){ nums[idx] = now; nums[idx + 1] = now; idx += 2; } else if(cnt == 1){ nums[idx] = now; ++idx; } } int removeDuplicates(vector<int>& nums) { int sz = nums.size(); int cnt = 0, idx = 0, now; for(int i = 0; i < sz; ++i){ if(i == 0) now = nums[i]; if(nums[i] == now){ ++cnt; } else { Count(nums, cnt, idx, now); cnt = 1; now = nums[i]; } } Count(nums, cnt, idx, now); return idx; }};
0 0
- 80. Remove Duplicates from Sorted Array II
- 80.Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 教你使用免费的BMFont工具和Photoshop来制作纹理贴图和fnt文件
- MAC安装Securecrt破解
- 关于java中Exception的一些理解
- 华为经典C语言面试题(二)
- UIAlertController浅见
- 80. Remove Duplicates from Sorted Array II
- Linux学习
- linux文件传输rz
- 大话cocos2d中的文字显示(CCLabelTTF、CCLabelBMFont和CCLabelAtlas)
- 5. Longest Palindromic Substring 暴力 800ms -> dp 97ms -> 回归原始 3ms AC
- 走进Python世界(7)----循环
- Error:Execution failed for task ':app:processDebugManifest'. > Manifest merger failed with multiple
- 连续第九十四天
- 手把手教你制作那个风靡的flappy bird小游戏(一)