Finding the second smallest integer in array

后端 未结 19 1907
無奈伤痛
無奈伤痛 2021-01-18 05:48

We are required in our assignment to find the second smallest integer in one array recursively. However, for the sake of understanding the subject more, I want to do it iter

19条回答
  •  鱼传尺愫
    2021-01-18 06:35

    How about this?

       int[] result = Arrays.asList(-3, 4,-1,-2).stream()
                .reduce(new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE},
                        (maxValues, x) -> {
                            if (x > maxValues[0]) {
                                maxValues[1] = maxValues[0]; //max becomes second max
                                maxValues[0] = x;
                            }
                            else if (x > maxValues[1]) maxValues[1] = x;
                            return maxValues;
                        }
                        , (x, y) -> x);
    

提交回复
热议问题