Java 如何获得三个最高整数的索引';数组的类型?
我正试图以3个最高分获得一次胜利。我试过了,但它没有按预期的方式工作。有人能帮我吗Java 如何获得三个最高整数的索引';数组的类型?,java,arrays,Java,Arrays,我正试图以3个最高分获得一次胜利。我试过了,但它没有按预期的方式工作。有人能帮我吗 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;
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]
}
public intgetscore(intteamnumber){//scores=[100,25,55,15,17]
返回此。分数[teamnumber-1];
}
公共int[]top3(){
int[]复制=分数;
int[]out=新的int[3];
int max=0;
int=0;
for(int i=1;i!=3;i++){
对于(int j=1;j!=copy.length+1;j++){
如果(最大值
试试这个
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;
}
int[]top3(int-arr[]){
int[]top=新的int[3];
第一,第二,第三;
第三个=第一个=第二个=整数.MIN_值;
对于(int i=0;ifirst){
第三=第二;
第二=第一;
第一个=arr[i];
}
else如果(arr[i]>second){
第三=第二;
秒=arr[i];
}
否则如果(arr[i]>第三个)
第三=arr[i];
}
top[0]=第一;
top[1]=第二;
top[2]=第三名;
返回顶部;
}
那么大体上
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]);
}
}
publicstaticvoidmain(字符串[]args){
int[]arr={5,8,2,3,6};
int[]top3=top3(arr);
对于(int i=0;i
当然,这不是解决这个问题的最有效方法。最好的方法是对数组进行排序,如果按升序排序,则检索最后3个元素。检查这一个
进口:
代码:
public int[]top3(int[]arr){
int-ranking_slots=3;
int[]排名=新的int[排名槽];
Arrays.sort(arr,Collections.reverseOrder());
对于(int pos=0;pos
只是想问一下:排序数组不是这里的一个选项吗?实际上,我很确定这是最有效的,因为排序数组的时间复杂度为O(nlogn),而您在这里发布的这个方法的时间复杂度为O(n),这对于越来越大的数组来说更快。当然,对数组进行排序会更快地输入!
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;
}