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代碼的實現(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); }}
運行結(jié)果:
相關(guān)文章:
1. docker-compose中volumes的問題2. vim - docker中新的ubuntu12.04鏡像,運行vi提示,找不到命名.3. docker 下面創(chuàng)建的IMAGE 他們的 ID 一樣?這個是怎么回事????4. python 多進(jìn)程 或者 多線程下如何高效的同步數(shù)據(jù)?5. angular.js - node.js中下載的angulae無法引入6. php - 想要遠(yuǎn)程推送emjio ios端怎么搞 需要怎么配合7. java - Hibernate查詢的數(shù)據(jù)是存放在session中嗎?8. 一個走錯路的23歲傻小子的提問9. android - 添加multidex后在部分機(jī)型上產(chǎn)生anr的問題,該如何解決10. docker-compose 為何找不到配置文件?
