Remove Duplicates from Sorted Array II

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]
分析
加一个变量记录一下元素出现的次数即可。这题因为是已经排序的数组,所以一个变量即可解
决。如果是没有排序的数组,则需要引入一个 hashmap 来记录出现次数。

代码

 1 public class solution {
 2 
 3     public static void main(String[] args) {
 4         
 5         int[] A= {1,1,1,2,2,3};
 6         int n = A.length;
 7         int index=removeDuplicates(A,n);
 8         int[] B=new int[index];     //定义好数组长度不好改
 9         for(int i=0;i<index;i++) {
10             B[i]=A[i];
11             System.out.println(B[i]);
12         }
13 
14     }
15     public static int removeDuplicates(int A[], int n) {
16         if (n == 0) return 0;
17         int occur = 1;
18         int index = 0;
19         for (int i = 1; i < n; i++) {
20           if (A[index] == A[i]) {
21              if (occur < 2) {
22                  A[++index] = A[i];
23                  occur++;
24              }
25            } else {
26                   A[++index] = A[i];
27                   occur = 1;
28                  }
29         }
30     
31         return index + 1;
32     }
33 }

 

posted @ 2018-06-11 15:00  昵称真难想  阅读(94)  评论(0编辑  收藏  举报