• 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^)/ ~ 「干货分享,每天更新」

  • 相关阅读:
    让ubuntu bash像git bash一样
    K8S-1.18.20高可用集群之部署集群监控系统kube-prometheus插件
    day03-2-拓展
    selenium爬虫如何绕过反爬,看这一篇文章就足够了
    60.WEB渗透测试-信息收集- 端口、目录扫描、源码泄露(8)
    成为年薪200W的云原生工程师,需要做什么?
    21.Redis之分布式锁
    泛型的类型擦除
    【Unity入门计划】Unity2D动画(2)-脚本与混合树实现玩家角色动画过渡
    CUDA向量相加 向量内积
  • 原文地址:https://blog.csdn.net/qq_26470817/article/details/126929360