java - topN排序问题求解。

查看:101
本文介绍了java - topN排序问题求解。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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

解决方案

你定义一个 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);
    }
}

运行结果:

这篇关于java - topN排序问题求解。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆