Created
January 21, 2013 14:30
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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