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]
.
“删除重复元素”的延续:
如果重复被允许至多两次又怎样呢?
例如:
给定排序了的数组 A = [1,1,1,2,2,3]
,
你的函数应该返回长度 s ,并且现在的A 是 [1,1,2,2,3]
.
此题想到了用哈希来做,但是发现Java中的HashMap不支持按照读入顺序读出,于是使用LinkedHashMap。
Java:
public int removeDuplicates(int[] A) { LinkedHashMap<Integer,Integer> map = new LinkedHashMap<Integer,Integer>(); for (int i = 0; i < A.length; i++) {//对元素的出现次数做记录 if (map.containsKey(A[i])) map.put(A[i], map.get(A[i]) + 1); else map.put(A[i], 1); } int sum=0;//计算最后数组需要的长度 for (Map.Entry<Integer,Integer> m : map.entrySet()){ if(m.getValue() >2) sum += 2; else sum += m.getValue(); } int i=0;//对新数组赋值 for (Map.Entry<Integer,Integer> m : map.entrySet()){ if(m.getValue() > 1){ int temp = A[i++] = m.getKey(); A[i] = temp; }else{ A[i] = m.getKey(); } i++; } return sum; }