LeetCode 1122. Relative Sort Array (数组的相对排序)

题目标签:Sort

  先设立一个 size 1000 的 array cnt [], 把arr1 里面的数字 计数存入 cnt;

  遍历 arr2, 按照arr2 的顺序把 arr1 与 arr2 重复的数字 先存入 arr1;

  遍历 cnt,把 cnt 里面剩余的 arr1 剩下的数字 存入arr1;

  具体看code。   

Java Solution: 

Runtime:  0 ms, faster than 100.00 % 

Memory Usage: 38 MB, less than 100.00 %

完成日期:03/12/2020

关键点:建立 array cnt 计数

class Solution {
    public int[] relativeSortArray(int[] arr1, int[] arr2) {
        int[] cnt = new int[1001];
        // save counts from arr1 into cnt
        for(int n : arr1) 
            cnt[n]++;
        
        // put same arr2 numbers into arr1 from cnt according to arr2 order
        int i = 0;
        for(int n : arr2) {
            while(cnt[n]-- > 0){
                arr1[i++] = n;
            }
        }
        
        // put the rest number from arr1 into cnt; cnt is in order already.
        for(int n = 0; n < cnt.length; n++) {
            while(cnt[n]-- > 0) {
                arr1[i++] = n;
            }
        }
        
        return arr1;
    }
}

参考资料:LeetCode Discuss

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

原文地址:https://www.cnblogs.com/jimmycheng/p/12495783.html