Remove Duplicates from Sorted Array II

来源:互联网 发布:java 二维码 编辑:程序博客网 时间:2024/06/05 03:11

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);elsemap.put(A[i], 1);}int sum=0;//计算最后数组需要的长度for (Map.Entry<Integer,Integer> m : map.entrySet()){if(m.getValue() >2)sum += 2;elsesum += 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;    }


0 0
原创粉丝点击