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. 文件服务器 - Python服务器之间文件同步如何实现?2. pdo 写入到数据库的内容为中文的时候写入乱码3. PHP类封装的插入数据,总是插入不成功,返回false;4. 网页爬虫 - python+requests 网页重定向求解5. 如何使用mysql查询每个用户一次操作时记录的值6. 管理员编辑,这么写页面没有反应是怎么回事,我哪里弄错了?7. javascript - vue1.0在微信浏览器的兼容性?8. mysql 时间类型 字段(精确到时分秒) 怎么比较?9. javascript - onfocus="this.type=’password’",为什么不直接用type=’password’10. python3.x - 我把3.6的卸载了,也重启了,但是在cmd用python -V指令查看版本时,还是提示下图的python3.6