Java – finds the second min element from the array

Anyone can convert it in the Java function style (lambda):

public int findSecondMin(int arr[]) {

    int min = Integer.MAX_VALUE,secondMin = Integer.MAX_VALUE;
    for (int i = 0; i < arr.length; i++) {
        if (min > arr[i]) {
            secondMin = min;
            min = arr[i];
        } else if (secondMin > arr[i]) {
            secondMin = arr[i];
        }
    }
    return secondMin;
}

I tried applying a filter, but it didn't work

Solution

With intstream, you can easily sort it and skip the first element:

public int findSecondMin(int[] arr)
{
    return IntStream.of(arr).sorted().skip(1).findFirst().orElse(Integer.MAX_VALUE);
}

But, of course, you don't have to use streams java. util. Arrays has a good sorting method, and then you can take the second element:

public int findSecondMin(int[] arr)
{
    Arrays.sort(arr);
    return arr.length < 2 ? Integer.MAX_VALUE : arr[1];
}

To avoid sorting the entire array, we can adopt your method and adjust it to a custom reduction in the stream:

public int findSecondMin(int[] arr)
{
    return IntStream.of(arr).@R_398_2419@ed().reduce(
        new int[] {Integer.MAX_VALUE,Integer.MAX_VALUE},(mins,i) -> {
            return new int[] {Math.min(i,mins[0]),Math.min(Math.max(i,mins[1])};
        },(mins1,mins2) -> {
            int[] lesser = mins1[0] < mins2[0] ? mins1 : mins2;
            int[] larger = mins1[0] < mins2[0] ? mins2 : mins1;
            return new int[] {lesser[0],Math.min(lesser[1],larger[0])};
        }
    )[1];
}

Compared with the implementation based on the for loop, it may be more difficult to read, but it can work in parallel

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>