java - topN排序问题求解。
阿神
阿神 2017-04-18 10:48:07
0
1
492

有个字符串数组,string[] str = {A,B,C,D,E,F,G,H};,数组分别对应一个整数数组,int[] a = {3,2,6,4,8,9,1,23};,类似于这样,对整数数组中的数从大到小排序,然后将整数数组对应的字符串数组按序输出,求解java代码的实现方式。

阿神
阿神

闭关修行中......

全部回覆(1)
Peter_Zhu

你定義一個 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;
        }

        @Override
        public 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);
    }
}

運行結果:

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!