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;
}
本文探讨了一种处理排序数组中重复元素至多两次的算法,通过使用LinkedHashMap来记录元素出现次数,并根据规则更新数组长度及内容。重点介绍了如何实现算法并优化数组结构。
239

被折叠的 条评论
为什么被折叠?



