LeetCode_1636_按照頻率將陣列升序排序

Fitz1318發表於2020-11-06

題目連結

解題思路

  • 頻次高位,原值取反(降序),拼接正數,排序後還原原值。

  • 首先注意到1 <= nums.length <= 100,-100 <= nums[i] <= 100

  • 所以設定一個tmp[201]用來記錄nums中數的頻率

  • 原值取反,拼接正數:然後對每個數,令其為頻率 * 1000 - nums[i] + 100

  • 之後進行排序,這樣子就即按頻率升序,又按照各自數值降序

  • 最後返回100 - nums[i] % 1000

AC程式碼

class Solution {
    public int[] frequencySort(int[] nums) {
        int[] tmp = new int[201];
        for (int n : nums)
            tmp[n + 100]++;
        for (int i = 0; i < nums.length; i++)
            nums[i] = tmp[nums[i] + 100] * 1000 - nums[i] + 100;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++)
            nums[i] = 100 - nums[i] % 1000;
        return nums;
    }
}

本地測試程式碼

package com.company;

import java.util.Arrays;

public class Solution_1636 {
    public static int[] frequencySort(int[] nums) {
        int[] tmp = new int[201];
        for (int n : nums)
            tmp[n + 100]++;
        for (int i = 0; i < nums.length; i++)
            nums[i] = tmp[nums[i] + 100] * 10000 - nums[i] + 100;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++)
            nums[i] = 100 - nums[i] % 10000;
        return nums;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(frequencySort(new int[]{1, 1, 2, 2, 2, 3})));
        System.out.println(Arrays.toString(frequencySort(new int[]{2, 3, 1, 3, 2})));
        System.out.println(Arrays.toString(frequencySort(new int[]{-1, 1, -6, 4, 5, -6, 1, 4, 1})));
    }
}

相關文章