如何获得数组中三个最高int的索引?

uklbhaso  于 2021-06-27  发布在  Java
关注(0)|答案(2)|浏览(298)

我想以三个最高分获得一个阿雷。我试过了,但效果不好。有人能帮我吗

public int getScore(int teamnumber) { // scores = [100, 25, 55, 15, 17]
    return this.scores[teamnumber-1];
}
public int[] top3() {
    int[] copy = scores;
    int[] out = new int[3];
    int max = 0;
    int biggest = 0;
    for (int i = 1; i != 3; i++) {
        for (int j = 1; j != copy.length + 1; j++) {
            if (max < getScore(j)) {
                out[i - 1] = j;
                max = getScore(j);
                biggest = j;
            }
        }
        copy[biggest] = 0;
        max = 0;
    }
    return out; // returns [1,1,0]
}
yyyllmsg

yyyllmsg1#

看看这个。。。。
进口:

import java.util.Collections;
import java.util.Arrays;

代码:

public int[] top3(int[] arr) {

        int ranking_slots = 3; 
        int [] ranking = new int[ranking_slots];

        Arrays.sort(arr, Collections.reverseOrder());

        for(int pos = 0; pos < ranking_slots; pos++){
        ranking[pos] = arr[pos];
        }
     return ranking;
     }
uurity8g

uurity8g2#

试试这个

int[] top3(int arr[]) { 
        int [] top = new int[3];
        int first, second, third; 

        third = first = second = Integer.MIN_VALUE; 
        for (int i = 0; i < arr.length; i++) { 
            if (arr[i] > first) { 
                third = second; 
                second = first; 
                first = arr[i]; 
            } 
            else if (arr[i] > second) { 
                third = second; 
                second = arr[i]; 
            } 
            else if (arr[i] > third) 
                third = arr[i]; 
        } 
        top[0] =first; 
        top[1] = second; 
        top[2] = third;

        return top;    
    }

然后在主要

public static void main(String[] args) {
        int[] arr = {5,8,2,3,6};
        int[] top3 = top3(arr); 

        for(int i = 0; i < top3.length; i++){
         System.out.println(i+1 + " = " + top3[i]);
        }

    }

当然,这不是解决这个问题最有效的方法。最好的方法是对数组排序,如果按升序排序,则检索最后3个元素。

相关问题