java完成給出分數數組獲得對應名次數組的辦法。本站提示廣大學習愛好者:(java完成給出分數數組獲得對應名次數組的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是java完成給出分數數組獲得對應名次數組的辦法正文
本文實例講述了java完成給出分數數組獲得對應名次數組的辦法。分享給年夜家供年夜家參考。詳細完成辦法以下:
package test01;
/**
* 給出分數數組,獲得對應的名次數組
* 列若有:score = {4,2,5,4}
* 則輸入:rank = {2,3,1,2}
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ScoreRank {
// 輸入數組
public static void show(int[] s){
for(int x:s) System.out.print(x);
System.out.println();
}
// 獲得名次
public static int[] scoreRank(int[] score) {
int[] temp = new int[score.length];
List lis = new ArrayList();
for(int x:score) // 添加元素(不反復)
if(!lis.contains(x)) lis.add(x);
Collections.sort(lis); // 從小到年夜排序
Collections.reverse(lis); // 從年夜到小排序
for(int i=0;i<score.length;i++) // 下標從 0 開端
temp[i] = lis.indexOf(score[i])+1;
// 所以:正常名次 = 獲得下標 + 1
return temp;
}
public static void main(String[] args){
int[] score = {4,2,5,4}; // 名次 {2,3,1,2}
int[] rank = scoreRank(score); // 獲得名次
System.out.print("原始分數:");show(score);
System.out.print("對應名次:");show(rank);
}
}
運轉成果以下:
原始分數:4254
對應名次:2312
願望本文所述對年夜家的java法式設計有所贊助。