首页 > 解决方案 > 获取双精度数组中的唯一元素 - Java

问题描述

如何获取在双数组中出现一次的元素?下面是我尝试过的,执行时间不可接受。这将针对非常庞大的数组运行。只能有一个独特的元素。

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;
}

标签: javaarrays

解决方案


你可以做这样的事情,这将计算 a 中的所有双打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;
}

推荐阅读