今日Leetcode的排序問題2191. Sort the Jumbled Numbers,主要有兩個部份,一個是把數字轉成另一個數字,用int就行,採Least Significant Digit First。然後排序,不建議用自訂Lambda,跑能過但非常慢;更不建議自製車輪去排序。比較快的方式是sort ((mapping(x), index),然後再從排序後的資料中取得 x
[Python code請進]
[Python code請進]
--------------------
Define the function convert(x) to map x to the corresponding number w.r.t. mapping
Sort the tuples (convert(x), i, x) or the pairs (convert(x), i) . Get x from the sorted data.
- class Solution:
- def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:
- def convert(x):
- if x==0: return mapping[0]
- z=0
- pow10=1
- while x>0:
- q, r=divmod(x, 10)
- z+=mapping[r]*pow10
- x=q
- pow10*=10
- return z
- n=len(nums)
- mapNum=[]
- for i, x in enumerate(nums):
- mapNum.append([convert(x), i, x])
- mapNum.sort()
- for i in range(n):
- nums[i]=mapNum[i][2]
- return nums
沒有留言:
張貼留言