常用排序题目

数组的相对排序

代码:

package com.dreams.leetcode;

import java.util.Arrays;

/*
    根据另一个数组次序排序 前提
    1. 元素值均 >= 0  <=1000
    2. 两个数组长度 <= 1000
 */
public class E01Leetcode1122 {
    public int[] relativeSortArray(int[] arr1, int[] arr2) {
        int[] count = new int[1001];
        for (int i : arr1) {
            count[i]++;
        }
        System.out.println(Arrays.toString(count));
        // 2, 4, 1
        // 1  2  3
        // 1 1 2 2 2 2 3 原始count排序
        // 2 2 2 2 3 1 1 要求的
        int[] result = new int[arr1.length];
        int k = 0;
        for (int i : arr2) {
            while (count[i] > 0) {
                result[k++] = i;
                count[i]--;
            }
        }
        for (int i = 0; i < count.length; i++) {
            while (count[i] > 0) {
                result[k++] = i;
                count[i]--;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] arr1 = {3, 2, 1, 2, 2, 1, 2, 5, 4};
        int[] arr2 = {2, 3, 1};

        E01Leetcode1122 leetcode = new E01Leetcode1122();
        int[] result = leetcode.relativeSortArray(arr1, arr2);
        System.out.println(Arrays.toString(result));
    }
}

 

 

按照频率将数组升序排序

代码:

package com.dreams.leetcode;

import java.util.Arrays;

/**
 * 按出现频率排序 数据范围在 [-100, 100] 内
 */
public class E02Leetcode1636 {
    public int[] frequencySort(int[] nums) {
        // 1. 统计出现频率
        int[] count = new int[201];
        for (int i : nums) {
            count[i + 100]++;
        }
        // 2. 比较器 按频率升序、再按数值降序
        return Arrays.stream(nums).boxed().sorted((a, b) -> {
            int af = count[a + 100];
            int bf = count[b + 100];
            if (af < bf) {
                return -1;
            } else if (af > bf) {
                return 1;
            } else {
                return b - a;
            }
        }).mapToInt(Integer::intValue).toArray();
    }

    public static void main(String[] args) {
        int[] nums = {2, 3, 1, 3, 2};
        System.out.println(Arrays.toString(new E02Leetcode1636().frequencySort(nums)));
    }
}

 

参考

黑马数据结构

暂无评论

发送评论 编辑评论

|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇