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. mongoDB可視化軟件mongoVUE打不開?2. 百度收錄判斷實際測試沒效果3. 百度地圖api - Android 百度地圖 集成了定位,導航 相互的jar包有沖突?4. mongoDB批量插入文檔時,運行下面代碼,用MongoVUE查看數據庫,mongo庫中只存在一個文檔?不應該是20個嗎?5. 我的Apache卡在這里不動了怎么辦?6. 零基礎自學PHP應該從哪開始?7. css - 這些字體是怎么弄的?8. 局域網下,如何配置電腦A的phpstudy環境可以使多臺電腦訪問電腦A的msql數據庫9. vue.js - vue上傳代碼到git10. 用CSS3 box-sizing 屬性實現兩個并排的容器,如果想讓容器中間有間隔該如何實現
