[JavaScript] Easy to understand - detailed explanation and optimize from 9327ms to 588ms
Core Strategy\n\nThe description of this problem is long, but actually it\'s a simple situation. In short words, what we need to do is:\n- make a mapping functi
## Core Strategy\n\nThe description of this problem is long, but actually it\'s a simple situation. In short words, what we need to do is:\n- make a mapping function to map the current value to the real value for compare\n- sort the `nums` by compare the real value\n- return the sorted array with the origin values\n\nFor step 2 and step 3, I guess there won\'t be too much difference between different solutions.\nFor step 1, let\'s try it in different solutions.\n\n## Base Solution\n\nFor this solution, we could split the number from a string to an array. Then for every single digiet, we could call `map` function of array to do the mapping.\n\nThe positive for this solution is it\'s short and easy to write. But negative is it\'s too slow.\n\nHere\'s the code I submitted during the contest as a sample (9327ms):\n\n```js\nconst getRealValue = (mapping, value) => +((\'\' + value).split(\'\').map(v => mapping[v]).join(\'\'));\nconst sortJumbled = (mapping, nums) => nums.sort((a, b) => getRealValue(mapping, a) - getRealValue(mapping, b));\n```\n\n## Optimizing with cache\n\nTo optimize the base solution, since we need to call `getRealValue` many times during sorting, but we always do the calculation everytime. So here could be a large optimization.\n\nWe use an extra `cache` hashtable to save the mapping results first. Then for sorting, we just need to get the value from that hashtable.\n\nHere\'s a sample code from me (1580ms):\n\n```js\nconst getRealValue = (mapping, value) => +((\'\' + value).split(\'\').map(v => mapping[v]).join(\'\'));\nconst sortJumbled = (mapping, nums) => {\n  const cache = {};\n  for (const num of nums) {\n    cache[num] = getRealValue(mapping, num);\n  }\n  return nums.sort((a, b) => cache[a] - cache[b]);\n};\n```\n\n## Optimizing with better mapping function\n\nThen about the `getRealValue` function, it needs to convert the number to a string, and then `split`, and then `map`. Looks like it\'s too complex.\n\nTo optimize, we implement another `getRealValue` function, by math method to get every digit in number and do the mapping.\n\nHere\'s a sample code from me (588ms):\n\n```js\nconst getRealValue = (mapping, value) => {\n  if (value === 0) return mapping[0];\n  let realValue = 0;\n  let carry = 1;\n  while (value > 0) {\n    const digit = value % 10;\n    realValue += mapping[digit] * carry;\n    carry *= 10;\n    value = (value / 10) >> 0;\n  }\n  return realValue;\n};\nconst sortJumbled = (mapping, nums) => {\n  const cache = {};\n  for (const num of nums) {\n    cache[num] = getRealValue(mapping, num);\n  }\n  return nums.sort((a, b) => cache[a] - cache[b]);\n};\n```\n
['JavaScript']