简体   繁体   English

如何在不比较数组元素的情况下修改find​​Min以查找最小元素(使用findMax)

[英]How do I modify findMin to find the minimum element without comparing the array elements (use findMax )

// Method for getting the maximum value
public static int findMax(int[] inputArray) {
    int maxValue = inputArray[0];
    for (int i = 1; i < inputArray.length; i++) {
        if (inputArray[i] > maxValue) {
            maxValue = inputArray[i];
        }
    }
    return maxValue;
}

// Method for getting the minimum value
public static int findMin(int[] inputArray) {
    int minValue = inputArray[0];
    for (int i = 1; i < inputArray.length; i++) {
        if (inputArray[i] < minValue) {
            minValue = inputArray[i];
        }
    }
    return minValue;
}

How do I modify findMin to find the minimum element without comparing the array elements (use findMax )? 如何在不比较数组元素的情况下修改find​​Min以找到最小元素(使用findMax)?

Without further information about inputArray , for example knowing about some specific ordering of the elements, there's no better way to find the min / max element in a general order of randomly ordered elements without visiting each element once. 如果没有关于inputArray更多信息,例如了解元素的某些特定顺序,没有更好的方法来查找随机排序元素的一般顺序中的min / max元素,而无需访问每个元素一次。 That's all your methods do now, there are no wasted operations here. 这就是你现在所做的所有方法,这里没有浪费的操作。 The code is good as it is (after @rink.attendant.6 kindly reformatted properly). 代码很好(在@ rink.attendant.6之后正确地重新格式化了)。

My only suggestion for possible simplification is to use Java 8 streams: 我唯一可能的简化建议是使用Java 8流:

return Arrays.stream(inputArray).parallel().min().get();

and

return Arrays.stream(inputArray).parallel().max().get();

It's possible that this could achieve better performance than straight iteration by parallel processing of sublists. 通过并行处理子列表,这可能比直接迭代实现更好的性能。

Another potential optimisation is to find both the min and max in a single operation: 另一个潜在的优化是在单个操作中找到最小值和最大值:

IntSummaryStatistics stats = Arrays.stream(inputArray).summaryStatistics();
int min = stats.getMin();
int max = stats.getMax();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM