【Leetcode】Remove Duplicates from Sorted Array II

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

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if (n <= 2) return n;
 5         int i, j, k = 1;
 6         for (i = 0, j = 1; j < n; ++j) {
 7             if (A[i] != A[j]) {
 8                 A[++i] = A[j];
 9                 k = 1;
10             } else if (k == 1) {
11                 A[++i] = A[j];
12                 ++k;
13             }
14         }
15         return i + 1;
16     }
17 };
View Code
 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if (n <= 2) return n;
 5         int i, j;
 6         for (i = 1, j = 2; j < n; ++j) {
 7             if (A[j] != A[i - 1]) {
 8                 A[++i] = A[j];
 9             }
10         }
11         return i + 1;
12     }
13 };
View Code

 

posted @ 2014-03-16 16:50  小菜刷题史  阅读(96)  评论(0编辑  收藏  举报