Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1122. 数组的相对排序 #2

Open
pigpigever opened this issue Jul 19, 2019 · 0 comments
Open

1122. 数组的相对排序 #2

pigpigever opened this issue Jul 19, 2019 · 0 comments
Labels
数组 数组类型的算法题

Comments

@pigpigever
Copy link
Owner

点击查看原题
关于解这道题的思路:

  • arr1 数组中跟 arr2 中存在交集的部分,按照在 arr2 数组中的顺序先排序
  • 排序完后,arr1 数组中剩余的部分按升序合并到之前的数组里

第一版程序:

/**
 * @param {number[]} arr1
 * @param {number[]} arr2
 * @return {number[]}
 */
var relativeSortArray = function(arr1, arr2) {
    let result = []

    while (arr2.length) {
        let i = arr1.length
        let target = arr2.pop()
        while (i--) {
            if (arr1[i] === target) {
                result.unshift(target)
                arr1.splice(i, 1)
            }
        }
    }
    return result.concat(arr1.sort((a, b) => a - b))
};

稍加思考后,觉得内层的 while 循环其实不必要。
第二版程序:

/**
 * @param {number[]} arr1
 * @param {number[]} arr2
 * @return {number[]}
 */
var relativeSortArray = function(arr1, arr2) {
    let result = [], i = 0, target
    while (true) {
        if (i === 0) {
            i = arr1.length
            target = arr2.pop()
        }
        if (arr1[--i] === target) {
            result.unshift(target)
            arr1.splice(i, 1)
        }
        if (!arr2.length && !i) {
            break
        }
    }
    return result.concat(arr1.sort((a, b) => a - b))
};
@pigpigever pigpigever added the 数组 数组类型的算法题 label Oct 13, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
数组 数组类型的算法题
Projects
None yet
Development

No branches or pull requests

1 participant