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 public class Solution {
 2     public int removeDuplicates(int[] A) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         Arrays.sort(A);
 6         int Len = 0;
 7         for (int i = 0; i < A.length; i++)
 8             if (i == 0 || A[i - 1] != A[i] || ( i != 0 && A[i] == A[i - 1] && (Len < 2 || A[Len - 1] != A[Len - 2])) )
 9                 A[Len ++] = A[i];
10         return Len;
11     }
12 }

 第三遍:

 1 public class Solution {
 2     public int removeDuplicates(int[] A) {
 3         if(A.length < 3) return A.length;
 4         int cur = 2;
 5         for(int i = 2; i < A.length; i ++){
 6             if(A[i] != A[cur - 2]) A[cur ++] = A[i];
 7         }
 8         return cur;
 9     }
10 }

 

posted on 2013-11-13 03:56  Step-BY-Step  阅读(191)  评论(0编辑  收藏  举报

导航