Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

按照频率将数组升序排序 #159

Open
yankewei opened this issue Sep 19, 2022 · 1 comment
Open

按照频率将数组升序排序 #159

yankewei opened this issue Sep 19, 2022 · 1 comment
Labels
哈希表 题目包含哈希表解法 排序 题目包含排序解法 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

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

请你返回排序后的数组。

示例 1:

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

示例 2:

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

示例 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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sort-array-by-increasing-frequency
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei yankewei added 简单 题目难度为简单 哈希表 题目包含哈希表解法 排序 题目包含排序解法 labels Sep 19, 2022
@yankewei
Copy link
Owner Author

class Solution {

    /**
     * @param Integer[] $nums
     * @return Integer[]
     */
    function frequencySort($nums) {
        $count_by_num = array_count_values($nums);
        usort($nums, function ($one, $two) use ($count_by_num) {
            if ($count_by_num[$one] === $count_by_num[$two]) {
                return $two <=> $one;
            }
            return $count_by_num[$one] <=> $count_by_num[$two];
        });

        return $nums;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
哈希表 题目包含哈希表解法 排序 题目包含排序解法 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant