图解LeetCode——1636. 按照频率将数组升序排序(难度:简单)

64 阅读1分钟

我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第19篇文章,点击查看活动详情

一、题目

给你一个整数数组 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实现排序

class Solution {
    public int[] frequencySort(int[] nums) {
        int[] result = new int[nums.length];
        Map<Integer, Integer> map = new HashMap();
        List<Integer> numsList = new ArrayList<>();
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
            numsList.add(num);
        }
        Collections.sort(numsList, (o1, o2) -> map.get(o1) != map.get(o2) ? map.get(o1) - map.get(o2) : o2 - o1);
        for (int i = 0; i < numsList.size(); i++) result[i] = numsList.get(i);
        return result;
    }
}

4.2> 使用Java Steam实现排序

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

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

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

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