Skip to content

Latest commit

 

History

History
51 lines (37 loc) · 1.32 KB

File metadata and controls

51 lines (37 loc) · 1.32 KB

2191. Sort the Jumbled Numbers

Leetcode link

题目简介

本题也是一个数组排序题,题目给了我们两个入参:

  • mapping:映射数组,代表下标到对应数字的映射,比如 [9] 代表数字 0 映射到数字 9
  • nums:需要被排序的数字数组

题目要求我们将 nums 的数字按照 mapping 映射之后的值升序排序,并且要求我们在元素映射后相等时不能改变对应的位置

解题思路

这一题只需要完成三步操作就可以解出:

  1. 求的 nums 中所有数字的映射值
  2. 根据映射值进行升序排序
  3. 排序过程中保证相等的元素相对位置不变(这个 js 的 sort 方法已经帮我们保证了这点)

Javascript

/**
 * @param {number[]} mapping
 * @param {number[]} nums
 * @return {number[]}
 */
var sortJumbled = function (mapping, nums) {
  	// 求得数字的映射值
    const transform = (num) => {
        return parseInt(
            num.
            toString().
            split('').
            map(item => mapping[item]).
            join(''))
    }

    const numMap = {};

    for(const num of nums) {
        numMap[num] = transform(num);
    }

  	// 根据映射值排序
    return nums.sort((a, b) => numMap[a] - numMap[b]);
};