pwstrick / daily

一份搜集的前端面试题目清单、面试相关以及各类学习的资料(不局限于前端)
2.39k stars 242 forks source link

数组的相对排序 #1023

Open pwstrick opened 4 years ago

pwstrick commented 4 years ago

1122. 数组的相对排序

/**
 * @param {number[]} arr1
 * @param {number[]} arr2
 * @return {number[]}
 */
var relativeSortArray = function(arr1, arr2) {
    const counts = [];
    arr1.forEach(value => {
        counts[value] = counts[value] ? (++counts[value]) : 1;
    });
    let merge = [];
    arr2.forEach(value => {
        const number = counts[value];
        merge = merge.concat(new Array(number).fill(value, 0));
        counts[value] = null;
    });
    counts.forEach((value, index) => {
        if(!value) return;
        merge = merge.concat(new Array(value).fill(index, 0));
    });
    return merge;
};