桶排序的思路

典型案例:arr1 [ 1, 2, 5, 2, 1, 8, 9, 5, 2, 8, 9, 10] 按照 arr2 [1, 5, 9, 8, 2, 10]的顺序排序

结果: [1,1,5,5,9,9,8,8,2,2,2,10]

思路:

function solution(arr1, arr2{
    const map = new Map(),
        len1 = arr1.length,
        len2 = arr2.length,
        res = []
    for (let i = 0; i < len2; i += 1) {
        map.set(arr2[i], [])
    }

    for (let i = 0; i < len1; i += 1) {
        const item = arr1[i]
        if (map.has(item)) {
          const temp = map.get(item)
          temp.push(item)
        }
    }

    map.forEach((value) => {
        res = res.concat(value)
    })

    return res
}

猜你喜欢

转载自www.cnblogs.com/rencoo/p/13381022.html