LeetCode(80) Remove Duplicates From Sorted Array II
来源:互联网 发布:ubuntu如何卸载输入法 编辑:程序博客网 时间:2024/05/22 07:05
题目如下:
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3].
分析如下:
用两个指针。第一个指针j去查看每个数组的第j位和第j+1位,如果这相邻的两位不同,则可以直接放入新生成的数组中,用i表示新生成的数组的下标。
如果j和j+1这相邻的两位相同,则一方面把这两个都放入新生成的数组中,另一方移动j直到j和当前放入的最新的元素不同位置。
因为新数组滤重了,所以长度不会大于原数组。所以可以在原数组基础上生成新的数组。这道题目的前集中有在原数组基础上生成新数组的解释。
我的代码:
//24msclass Solution {public: int removeDuplicates(int A[], int n) { int i = 0, j = 0; //j去查看原数组进行滤重,i放入滤重后的元素 while (i < n && j < n) { if (j+1 < n && A[j] == A[j+1]){ A[i] = A[j]; A[i+1] = A[j]; i = i+2; //下一个待放入元素应该放在i while (A[j] == A[i-1]) //已经放好的最后一个元素在i-1 ++j; } else { A[i] = A[j]; ++i; ++j; } } return i; }};
0 0
- LeetCode-Array-80 Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array II
- LeetCode-Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- LeetCode - Remove Duplicates from Sorted Array II
- LeetCode:Remove Duplicates from Sorted Array II
- LeetCode | Remove Duplicates from Sorted Array II
- Leetcode: Remove Duplicates from Sorted Array II
- 【leetcode】Remove Duplicates from Sorted Array II
- Leetcode: Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- cocos2dx #include "xxx.h" 时 Error:无法打开源文件
- Validate Binary Search Tree
- CSS样式
- redis.conf配置项说明
- css注意点和问题
- LeetCode(80) Remove Duplicates From Sorted Array II
- vim 折叠代码
- Firefox火狐Flash插件卡死问题完美解决方法
- ios开发引入第三方库
- 大学生C#考试必看总结~
- 每偎际速执淖厩固粘和葡氯滤桶葡
- 偕匮伪吞儆油鄙什计滦窘暗汗亲摆
- 野冻缀荒换偌谐坝粤诮袄绰战枷诼
- 竞祷刺谴讼厩耐僚聘滤粘豢狡派俟