求写一个java方法 形参传入数组和目标值,求距目标值最远的元素

如题所述

class Findtheloser {
    public static void main(String[] args) {
        int d = winnersearchKey(new int[]{1,2,3,4,5,6,7}, 4.2389485);
        System.out.println(d);
    }
    public static int winnersearchKey(int[] array, double targetNum) {
        Map<Double, Integer> map = new HashMap<Double, Integer>(array.length);
        for(int ele : array) {
            map.put(Math.abs(targetNum - ele), ele);
        }
        List<Double> tempLst = new ArrayList<Double>(map.keySet());
        Collections.sort(tempLst, new Comparator<Double>() {
            @Override
            public int compare(Double o1, Double o2) {
                return -o1.compareTo(o2);
            }
        });
        return map.get(tempLst.get(0));
    }
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-10-14
目标值最远?是指差值最大么?追问

对的,和目标值差值的绝对值要最大