[英]How to remove all duplicates from an array
I want to remove every duplicate from an array in Java and store the remaining integers in the same array. 我想从Java中的数组中删除每个副本,并将剩余的整数存储在同一个数组中。
Eg: int[] = { 5,5,5,3,4,4,2,2,1}; 例如:int [] = {5,5,5,3,4,4,2,2,1}; ==> int[] = {3,1}; ==> int [] = {3,1};
So far I have tried using: 到目前为止我尝试过使用:
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < array.length; i++) {
set.add(array[i]);
}
It appears though, that this only removes one of the duplicates and not both. 但看起来,这只会删除其中一个副本,而不是两者。
Any help would be appreciated. 任何帮助,将不胜感激。
This should work : 这应该工作:
int[] array = { 5,5, 5, 3, 4, 4, 2, 2, 1}; int [] array = {5,5,5,3,4,4,2,2,1};
Arrays.sort(array);
Set<Integer> set = new HashSet<Integer>();
Set<Integer> duplicateSet = new HashSet<Integer>();
for (int i = 0; i < array.length; i++) {
if(!set.add(array[i])){
duplicateSet.add(array[i]);
}
}
System.out.println(duplicateSet.toString());
set.removeAll(duplicateSet);
System.out.println(set.toString());
output : 输出:
[1,3]
You can use a HashMap to maintain the count of each element and remove those elements that have count greater than 1. 您可以使用HashMap来维护每个元素的计数,并删除那些计数大于1的元素。
public int[] removeDuplicates(int[] arr) {
Map<Integer, Integer> countMap = new LinkedHashMap<>(); // To maintain the order
for (int n : arr) {
Integer count = countMap.get(n);
if (count == null) {
count = 0;
}
count++;
countMap.put(n, count);
}
for(Iterator<Map.Entry<String, String>> it = countMap.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, String> entry = it.next();
if (entry.getValue() > 1) {
it.remove();
}
}
return new ArrayList<>(countMap.keySet()).toArray(new int[0]);
}
You don't even a set, it is very simple, convert the array to a List and then use Collections.frequency
to check for duplicates as shown below: 你甚至没有一个集合,它非常简单,将数组转换为List,然后使用Collections.frequency
检查重复项,如下所示:
Integer[] array = { 5,5,5,3,4,4,2,2,1};
List<Integer> listInputs = Arrays.asList(array);
List<Integer> listOutputs = new ArrayList<>();
for(int value : listInputs) {
if(Collections.frequency(listInputs, value) ==1) {
listOutputs.add(value);
}
}
System.out.println(listOutputs);
OUTPUT: [3, 1] 输出:[3,1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.