简体   繁体   English

如何在数组中找到最大值及其位置

[英]How to find the highest value in an array and its position

So I have an array and I know how to find the highest value but I can't figure out how to obtain the position of that value in the array. 所以我有一个数组,我知道如何找到最大值,但我不知道如何获取该值在数组中的位置。 The method so far is as follows: 到目前为止的方法如下:

 public static void findHottest(int[] temp){
        int hottest = temp[0];
        for(int i = 1; i < temp.length; i++){
            if(temp[i] > hottest) {
                hottest = temp[i];
            }
        }
public static void findHottest(int[] temp){
    int hottest = temp[0];
    int highestIndex = 0;

    for(int i = 1; i < temp.length; i++){
        if(temp[i] > hottest) {
            hottest = temp[i];
            highestIndex = i;
    }
}

Just store the index when you encounter a higher value. 当遇到更高的值时,只需存储索引。

You already have the answer. 您已经有了答案。 In your code 在你的代码中

    public static void findHottest(int[] temp){
            int hottest = temp[0];
int index =0;
            for(int i = 1; i < temp.length; i++){
                if(temp[i] > hottest) {
                    hottest = temp[i]; 
                    index =i // index is the index you are looking for.
                }
            }

So, just have an index variable that gets updated whenever hottest = temp[i] statement gets executed. 因此,只要有一个index变量,只要执行hottest = temp[i]语句就可以更新。

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

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