[leetcode] Remove Duplicates from Sorted Array II
2013-04-03 20:21
387 查看
Remove Duplicates from Sorted Array IIApr
19 '12
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A =
Your function should return length =
and A is now
第一种解法是记录当前节点出现的次数,大于两次就将后面的节点向前搬,但是对结尾处的节点要拉出来处理,比较繁杂。
19 '12
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].
第一种解法是记录当前节点出现的次数,大于两次就将后面的节点向前搬,但是对结尾处的节点要拉出来处理,比较繁杂。
class Solution { public: int removeDuplicates(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function if(n<1) return 0; int i=1; int cnt=0; while(i<n) { if(A[i]==A[i-1]) { cnt++; if(cnt<2) i++; else { if(i==n-1) n--; else { for(int j=i+1; j<n; j++) { A[j-1]=A[j]; } n--; } } } else { cnt=0; i++; } } return n; } };另一种解法是设置两个下标,用state表明当前节点是第几次出现,若不是连续第3次出现,则将后面下标的节点搬到前面下标记录的位置上去。
class Solution { public: int removeDuplicates(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int ans = 0; int state; for(int i = 0;i < n;i++) { if(i == 0 || A[i] != A[i-1]) { A[ans++] = A[i]; state = 1; } else if(state == 1) { state++; A[ans++] = A[i]; } } return ans; } };
相关文章推荐
- LeetCode:Remove Duplicates from Sorted Array I&&II
- 【leetcode】【80】Remove Duplicates from Sorted Array II
- LeetCode 080 Remove Duplicates from Sorted Array II
- leetcode-26&80 Remove Duplicates from Sorted Array I & 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 c++】80 Remove Duplicates from Sorted Array II
- [LeetCode][Java] Remove Duplicates from Sorted Array II
- (leetcode) Remove Duplicates from Sorted Array II
- Leetcode 之 Remove Duplicates from Sorted Array II
- leetcode-26&80 Remove Duplicates from Sorted Array I&II
- 80. Remove Duplicates from Sorted Array II LeetCode
- [LeetCode] Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II 从有序数组里移除重复出现元素,最多重复出现2次 @LeetCode
- leetcode:Remove Duplicates from Sorted Array II
- LeetCode Remove Duplicates from Sorted Array II