在我的程序中,我有一个数组,我必须找出数组中的哪个位置具有最高值。唯一的问题是,如果数组中的两个或多个位置存在最高值怎么办?
这些是找到最高值的方法,但如果最高值在另外两个地方相同,它们就不起作用了?
for (int counter = 1; counter < decMax.length; counter++)
{
if (decMax[counter] > max)
{
max = decMax[counter];
}
}
System.out.println("The highest maximum for the December is: " + max);
public int maxValue(int array[]){
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
list.add(array[i]);
}
return Collections.max(list);
}
public int maxValue(int array[]){
int max = Arrays.stream(array).max().getAsInt();
return max;
}
最佳答案
您可以返回 List<Integer>
具有找到最大值的位置/索引。
当您找到max
时用它来查找它在数组中存在的索引:
public List<Integer> maxValue(int array[]){
int max = Arrays.stream(array).max().orElse(-1);
return IntStream.range(0, array.length)
.filter(idx -> array[idx] == max)
.mapToObj(i -> i)
.collect(Collectors.toList());
}
关于java - 查找数组中的最高值,但是如果最高值在数组中存在两个或多个位置怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57904515/