如何获取在双精度数组中出现一次的元素?下面是我尝试过的,执行时间不可接受。这将针对非常庞大的阵列。唯一元素只能是一个。
public static double getUnique(double arr[]) {
double res = 0.0;
for (int i = 0; i < arr.length; i++){
res = arr[i];
int count = 0;
for (int j = 0; j < arr.length; j++){
if (res == arr[j]){
count ++;
}
if(j == arr.length - 1){
if(count == 1){
return res;
}
}
}
}
return res;
}
答案 0 :(得分:0)
您可以执行以下操作,这将计算HashMap
中的所有双打并返回出现次数为double
的第一个1
:
public static double getUniqueMine(double arr[]) {
// Keep track of the occurances of doubles
HashMap<Double, Integer> doubleOccurances = new HashMap<>();
// Loop through all doubles
for(double d : arr) {
// Increment double count
doubleOccurances.merge(d, 1, Integer::sum);
}
// Return the first item where the count is 1
for(Entry<Double, Integer> values : doubleOccurances.entrySet()) {
if(values.getValue() == 1) {
return values.getKey();
}
}
return 0.0;
}
答案 1 :(得分:0)
使用流:
如果您确定总是有一个唯一元素:
public static double getUnique(double arr[]) {
return Arrays.stream(arr).boxed()
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
.entrySet().stream().filter(e->e.getValue() == 1).findFirst().get().getKey();
}
否则,使用以下方法返回默认值:
public static double getUnique2(double arr[]) {
return Arrays.stream(arr).boxed()
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
.entrySet().stream().filter(e->e.getValue() == 1)
.map(Map.Entry::getKey).findFirst().orElse(-1.);
}