java - topN排序問題求解。
問題描述
有個字符串數組,string[] str = {A,B,C,D,E,F,G,H};,數組分別對應一個整數數組,int[] a = {3,2,6,4,8,9,1,23};,類似于這樣,對整數數組中的數從大到小排序,然后將整數數組對應的字符串數組按序輸出,求解java代碼的實現方式。
問題解答
回答1:你定義一個 Holder 類,用來保存 字符-數字 這個映射,然后對所有的 Holder,按照 Holder 中的數字從大到小排序,最后按序輸出每個 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); }}
運行結果:
相關文章:
1. mysql - 這條聯(lián)合sql語句哪里錯了2. webpack - vuejs+java前后臺分離實現及部署問題3. docker容器呢SSH為什么連不通呢?4. docker start -a dockername 老是卡住,什么情況?5. docker鏡像push報錯6. python - 速度最快的啟動界面GUI7. 網站在移動的環(huán)境下手機,pc打不開8. python - pip install出現下面圖中的報錯 什么原因?9. javascript - js 函數代碼,關于滾動加載數據10. javascript - stylus格式的圖標字體里url無法解析
