• 1636. 按照频率将数组升序排序(难度:简单)


    一、题目

    给你一个整数数组 nums ,请你将数组按照每个值的频率 升序 排序。如果有多个值的频率相同,请你按照数值本身将它们 降序 排序。 请你返回排序后的数组。

    二、示例

    2.1> 示例 1:

    【输入】nums = [1,1,2,2,2,3]
    【输出】[3,1,1,2,2,2]
    【解释】'3' 频率为 1,'1' 频率为 2,'2' 频率为 3 。

    2.2> 示例 2:

    【输入】nums = [2,3,1,3,2]
    【输出】[1,3,3,2,2]
    【解释】'2' 和 '3' 频率都为 2 ,所以它们之间按照数值本身降序排序。

    2.3> 示例 3:

    【输入】nums = [-1,1,-6,4,5,-6,1,4,1]
    【输出】[5,-1,4,4,-6,-6,1,1,1]

    提示:

    • 1 <= nums.length <= 100
    • -100 <= nums[i] <= 100

    三、解题思路

    对集合类的排序问题,我们可以采用Collections.sort的方式。

    其次,也可以采用JDK8中提供的Java Stream方式,由于这种需要传入Integer[]数组,那么我们可以通过调用boxed()方法将int[]数组转换为Integer[]数组,

    最后,可以通过调用mapToInt(Integer::intValue).toArray()的方式,从流中获得int[]数组。

    四、代码实现

    4.1> 使用Collections.sort实现排序

    1. class Solution {
    2.     public int[] frequencySort(int[] nums) {
    3.         int[] result = new int[nums.length];
    4.         Map<Integer, Integer> map = new HashMap();
    5.         List<Integer> numsList = new ArrayList<>();
    6.         for (int num : nums) {
    7.             map.put(num, map.getOrDefault(num, 0) + 1);
    8.             numsList.add(num);
    9.         }
    10.         Collections.sort(numsList, (o1, o2) -> map.get(o1) != map.get(o2) ? map.get(o1) - map.get(o2) : o2 - o1);
    11.         for (int i = 0; i < numsList.size(); i++) result[i] = numsList.get(i);
    12.         return result;
    13.     }
    14. }

    4.2> 使用Java Steam实现排序

    1. class Solution {
    2.     public int[] frequencySort(int[] nums) {
    3.         Map<Integer, Integer> map = new HashMap();
    4.         for (int num : nums) map.put(num, map.getOrDefault(num, 0) + 1);
    5.         return Arrays.stream(nums).boxed()
    6.                 .sorted(((o1, o2) -> map.get(o1) != map.get(o2) ? map.get(o1) - map.get(o2) : o2 - o1))
    7.                 .mapToInt(Integer::intValue).toArray();
    8.     }
    9. }

    今天的文章内容就这些了:

    写作不易,笔者几个小时甚至数天完成的一篇文章,只愿换来您几秒钟的 点赞 & 分享 。

    更多技术干货,欢迎大家关注公众号“爪哇缪斯” ~ \(^o^)/ ~ 「干货分享,每天更新」

  • 相关阅读:
    【21天打卡】前端攻城狮重学算法之-希尔排序
    条件分支和循环机制、标志寄存器及函数调用机制
    微服务系列之Api文档 swagger整合
    springboot+jsp汽车配件管理系统idea maven 项目lw
    ZABBIX新功能系列1-使用Webhook将告警主动推送至第三方系统
    web前端面试高频考点——Vue组件间的通信及高级特性(多种组件间的通信、自定义v-model、nextTick、插槽)
    程序员35岁之后有什么出路?
    vue3 自动导入composition-apiI和组件
    科普系列:AUTOSAR与OSEK网络管理比较(上)
    亚马逊鲲鹏系统六大优势
  • 原文地址:https://blog.csdn.net/qq_26470817/article/details/126929360