Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save pdu/4586460 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4586460 to your computer and use it in GitHub Desktop.
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]. http://leetcode.com/onlinejudge#question_80
class Solution {
public:
int removeDuplicates(int A[], int n) {
int id = 0;
int cur = 0;
while (cur < n) {
int cnt = 0;
int val = A[cur];
while (cur < n && val == A[cur]) {
cur++;
cnt++;
}
if (cnt == 1)
A[id++] = val;
else if (cnt >= 2) {
A[id++] = val;
A[id++] = val;
}
}
return id;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment