DEV Community

Karleb
Karleb

Posted on

#1122. Relative Sort Array

https://leetcode.com/problems/relative-sort-array/description/?envType=daily-question&envId=2024-06-11


/**
 * @param {number[]} arr1
 * @param {number[]} arr2
 * @return {number[]}
 */
var relativeSortArray = function(arr1, arr2) {
    const map = new Map()
    const N = arr2.length

    for(let i = 0; i < arr2.length; i++) {
        map.set(arr2[i], i)
    }

    return arr1.sort((a,b) => {
        a = map.has(a) ? map.get(a) : N + a
        b = map.has(b) ? map.get(b) : N + b
        return a - b
    })
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)