java - topN排序問題求解。
問題描述
有個字符串?dāng)?shù)組,string[] str = {A,B,C,D,E,F,G,H};,數(shù)組分別對應(yīng)一個整數(shù)數(shù)組,int[] a = {3,2,6,4,8,9,1,23};,類似于這樣,對整數(shù)數(shù)組中的數(shù)從大到小排序,然后將整數(shù)數(shù)組對應(yīng)的字符串?dāng)?shù)組按序輸出,求解java代碼的實(shí)現(xiàn)方式。
問題解答
回答1:你定義一個 Holder 類,用來保存 字符-數(shù)字 這個映射,然后對所有的 Holder,按照 Holder 中的數(shù)字從大到小排序,最后按序輸出每個 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. docker不顯示端口映射呢?2. angular.js - 關(guān)于$apply()3. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””4. macos - mac下docker如何設(shè)置代理5. MySQL數(shù)據(jù)庫中文亂碼的原因6. docker - 各位電腦上有多少個容器啊?容器一多,自己都搞混了,咋辦呢?7. docker gitlab 如何git clone?8. mysql - 新浪微博中的關(guān)注功能是如何設(shè)計表結(jié)構(gòu)的?9. css - C#與java開發(fā)Windows程序哪個好?10. docker-compose 為何找不到配置文件?
