LeetCode: Remove Duplicates from Sorted Array II(在排序数组中删除重复元素)
2015-01-31 10:52
621 查看
原题: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].
在元素递增的数组中,删除必要元素,使得单个元素的重复次数<=2。
首先可以想到的是用双指针,然后对元素重复次数计数,可以在O(N)时间内完成处理。
这里还有更精简伶俐的写法:判断当前快指针所指元素是否与慢指针之前的那个元素相同,如果不相同那么重复次数一定小于3,即可满足条件。
参考:https://oj.leetcode.com/discuss/2754/is-it-possible-to-solve-this-question-in-place
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].
在元素递增的数组中,删除必要元素,使得单个元素的重复次数<=2。
首先可以想到的是用双指针,然后对元素重复次数计数,可以在O(N)时间内完成处理。
class Solution { public: int removeDuplicates(int A[], int n) { if(A==NULL || n<=0) return 0; int slow = 0, fast = 0; int times = 1; while(++fast<n){ if(A[fast]==A[fast-1]){ if(++times<=2)//判断重复次数是否小于等于2 A[++slow] = A[fast]; }else{ times = 1;//遇到新元素则计数置一 A[++slow] = A[fast]; } } return slow+1; } };
这里还有更精简伶俐的写法:判断当前快指针所指元素是否与慢指针之前的那个元素相同,如果不相同那么重复次数一定小于3,即可满足条件。
class Solution { public: int removeDuplicates(int A[], int n) { if(A==NULL || n<=2) return n; int slow = 1, fast = 1; while(++fast<n){ if(A[fast]!=A[slow-1]) A[++slow] = A[fast]; } return slow+1; } };
参考:https://oj.leetcode.com/discuss/2754/is-it-possible-to-solve-this-question-in-place
相关文章推荐
- [Leetcode] Remove duplicates from sorted array ii 从已排序的数组中删除重复元素
- 【LeetCode-面试算法经典-Java实现】【026-Remove Duplicates from Sorted Array(删除排序数组中的重复元素)】
- leetcode 题解:Remove Duplicates from Sorted Array II(已排序数组去三次及以上重复元素)
- [Leetcode] Remove duplicates from sorted array 从已排序的数组中删除重复元素
- Leetcode刷题记—— Remove Duplicates from Sorted Array II(已排序数组移除重复元素2)
- LeetCode Remove Duplicates from Sorted Array II 删除整型数组中的重复元素并返回剩下元素个数2
- LeetCode | Remove Duplicates from Sorted Array II(删除重复的元素2)
- LeetCode 26 Remove Duplicates from Sorted Array(从已排序数组中移除重复元素)
- lintcode 容易题:Remove Duplicates from Sorted Array II 删除排序数组中的重复数字 II
- LeetCode-26-Remove Duplicates from Sorted Array(消除已排序数组中的重复元素)
- Leetcode刷题记——26. Remove Duplicates from Sorted Array(删除数组重复元素)
- 【LeetCode-面试算法经典-Java实现】【082-Remove Duplicates from Sorted List II(排序链表中删除重复元素II)】
- leetcode:Remove Duplicates from Sorted Array去掉排序数组中重复的元素
- LeetCode-Remove Duplicates from Sorted Array II (删除重复元素,使重复次数最多N次)
- LintCode Remove Duplicates from Sorted Array II 删除排序数组中的重复数字 II
- leetcode:26&80 Remove Duplicates from Sorted Array 删除数组中的重复元素
- Remove Duplicates from Sorted Array II 从有序数组里移除重复出现元素,最多重复出现2次 @LeetCode
- leetcode 26. Remove Duplicates from Sorted Array从排序数组中移出重复元素(双指针)
- LeetCode 26 Remove Duplicates from Sorted Array(从已排序数组中移除重复元素)
- LeetCode | Remove Duplicates from Sorted Array(删除有序数组的重复元素)