[Leetcode] Remove Duplicates From Sorted Array II (C++)

题目:

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].

Tag:

Array; Two Pointers

体会:

继续是quicksort中partition函数的改写。和Remove Duplicates From Sorted Array只有一处变化。这次的变化是第10处的那个判断条件多了一部分 A[len - 1] != A[i] 。从A[0]到A[len]是满足题意要求的部分, 如果现在正在检查的这个element已经在A[0]-A[len]出现过了,但是只要它在最近的两个中没有出现,还是可以加到现在的部分中的。

 class Solution {
public:
int removeDuplicates(int A[], int n) {
// length of satisfied part
int len = -;
for (int i = ; i < n; i++) {
// if it is unique to current satisfied part
// or it has not shown within last two positions
// in current satisfied part
if (A[i] != A[len] || A[len - ] != A[i]) {
len++;
A[len] = A[i];
}
}
return len + ;
}
};
上一篇:转:用​C​语​言​的​r​a​n​d​(​)​和​s​r​a​n​d​(​)​产​生​伪​随​机​数​的​方​法​总​结


下一篇:[LeetCode] Remove Duplicates from Sorted Array II [27]