2010-04-29 89 views
0

我有一个名为Names [5]的数组和一个名为scores [5] [5]的数组。 每一行都对应于相应索引中的名称。寻找数组中最好的人

我需要在scores数组中找到最高分数并返回与之对应的名称。

这是我到目前为止有:

int high = 0; 
for(a=0; a<5; a++) 
    for(b=0; b<5; b++) 
     if(high<scores[a][b]) 
+2

好的。那么你卡在哪里?你有多远?你究竟需要帮助弄清楚什么? – 2010-04-29 21:22:25

+0

您需要使用更好的数据结构。 – 2010-04-29 21:22:58

+0

我知道我将需要一个循环的配合才能确定逻辑如何工作 – dalton 2010-04-29 21:23:48

回答

4

只需扫描矩阵,记住最好成绩和最好的名字至今。 类似于:

String[] names = {"a","b","c","d","e"}; 
int[][] scores = new int[5][5]; 
//... init scores 

int best = Integer.MIN_VALUE; 
String bestName = null; 
for(int nm = 0;nm<5;nm++){ 
    for(int c = 0;c<5;c++){ 
     int score = scores[nm][c]; 
     if (score>=best){ 
      best = score; 
      bestName = names[nm]; 
     } 
    } 
} 
System.out.println(bestName); 
+0

ugh O(N^2)的东西应该是O(1)。数据结构的人。 – 2010-04-29 21:44:33

+0

Int最好= Integer.Min_value做什么 – dalton 2010-04-29 21:53:37

+0

@Byron:假设我们控制着收集分数的过程,我们可以在这个过程中保持最好的分数和人,然后在O(1)中返回它。但是这个问题涉及数据已经在矩阵中的给定情况。这里没有比O(n^2)更好的解决方案 – 2010-04-29 22:03:50