列表排序

1.普通的排序

Arrays.sort(nums);  //数组排序
Collections.sort(list);  //链表排序

2.按照数字出现的频次升序排序,如果频次相同按照数值本身大小降序排序

class Solution {
    public int[] frequencySort(int[] nums) {
        Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
        for(int k:nums){
            if(hm.get(k)==null){
                hm.put(k,0);
            }else{
                hm.put(k,hm.get(k)+1);
            }
        }
        List<Integer> list = new ArrayList<Integer>();
        for (int num : nums) {
            list.add(num);
        }
        Collections.sort(list, (a, b) -> {
            int cnt1 = hm.get(a), cnt2 = hm.get(b);
            return cnt1 == cnt2 ?  b - a:cnt1 - cnt2;
        });
        int length = nums.length;
        for (int i = 0; i < length; i++) {
            nums[i] = list.get(i);
        }
        return nums;
    }
}

 




posted @ 2022-09-19 17:12  StarZhai  阅读(65)  评论(0编辑  收藏  举报