您的位置:首頁技術文章
文章詳情頁

java - topN排序問題求解。

瀏覽:154日期:2024-02-07 15:47:53

問題描述

有個字符串數組,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); }}

運行結果:java - topN排序問題求解。

標簽: java
相關文章:
国产综合久久一区二区三区