java - topN排序問題求解。
問題描述
有個(gè)字符串?dāng)?shù)組,string[] str = {A,B,C,D,E,F,G,H};,數(shù)組分別對(duì)應(yīng)一個(gè)整數(shù)數(shù)組,int[] a = {3,2,6,4,8,9,1,23};,類似于這樣,對(duì)整數(shù)數(shù)組中的數(shù)從大到小排序,然后將整數(shù)數(shù)組對(duì)應(yīng)的字符串?dāng)?shù)組按序輸出,求解java代碼的實(shí)現(xiàn)方式。
問題解答
回答1:你定義一個(gè) Holder 類,用來保存 字符-數(shù)字 這個(gè)映射,然后對(duì)所有的 Holder,按照 Holder 中的數(shù)字從大到小排序,最后按序輸出每個(gè) Holder 的字符。
import java.util.Arrays;public class Test { static class Holder implements Comparable<Holder> {public int num;public String str;public Holder(String str, int num) { this.str = str; this.num = num;}@Overridepublic int compareTo(Holder that) { return that.num - this.num; // 逆序排序} } public static void test(String[] strs, int[] nums) {if (strs.length != nums.length) { return;}Holder[] holders = new Holder[strs.length];for (int i = 0; i < strs.length; i++) { holders[i] = new Holder(strs[i], nums[i]);}Arrays.sort(holders);for (Holder holder : holders) { System.out.print(holder.str + ' ');}System.out.println(); } public static void main(String[] args) throws Exception {String[] strs = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};int[] a = {3, 2, 6, 4, 8, 9, 1, 23};test(strs, a); }}
運(yùn)行結(jié)果:
相關(guān)文章:
1. python 利用subprocess庫調(diào)用mplayer時(shí)發(fā)生錯(cuò)誤2. python文檔怎么查看?3. python - Pycharm的Debug用不了4. javascript - 關(guān)于apply()與call()的問題5. datetime - Python如何獲取當(dāng)前時(shí)間6. javascript - nginx反向代理靜態(tài)資源403錯(cuò)誤?7. html - eclipse 標(biāo)簽錯(cuò)誤8. 請(qǐng)問PHPstudy中的數(shù)據(jù)庫如何創(chuàng)建索引9. 安全性測試 - nodejs中如何防m(xù)ySQL注入10. python - pycharm 自動(dòng)刪除行尾空格
