get closest value to a number in array

后端 未结 12 1823
庸人自扰
庸人自扰 2020-12-01 07:52

I have an array of positive/negative ints

int[] numbers = new int[10];
numbers[0] = 100;
numbers[1] = -34200;
numbers[2] = 3040;
numbers[3] = 400433;
numbers         


        
12条回答
  •  自闭症患者
    2020-12-01 08:36

    One statement block to initialize and set the closest match. Also, return -1 if no closest match is found (empty array).

     protected int getClosestIndex(final int[] values, int value) {
        class Closest {
            Integer dif;
            int index = -1;
        };
        Closest closest = new Closest();
        for (int i = 0; i < values.length; ++i) {
            final int dif = Math.abs(value - values[i]);
            if (closest.dif == null || dif < closest.dif) {
                closest.index = i;
                closest.dif = dif;
            }
        }
        return closest.index;
    }
    

提交回复
热议问题