herrDeng網內搜尋

自訂搜尋

Ads

2024年7月24日 星期三

Python C++速解排序問題Leetcode 2191 Sort the Jumbled Numbers


今日Leetcode的排序問題2191. Sort the Jumbled Numbers,主要有兩個部份,一個是把數字轉成另一個數字,用int就行,採Least Significant Digit First。然後排序,不建議用自訂Lambda,跑能過但非常慢;更不建議自製車輪去排序。比較快的方式是sort ((mapping(x), index),然後再從排序後的資料中取得 x
[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.

  1. class Solution:
  2. def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:
  3. def convert(x):
  4. if x==0: return mapping[0]
  5. z=0
  6. pow10=1
  7. while x>0:
  8. q, r=divmod(x, 10)
  9. z+=mapping[r]*pow10
  10. x=q
  11. pow10*=10
  12. return z
  13. n=len(nums)
  14. mapNum=[]
  15. for i, x in enumerate(nums):
  16. mapNum.append([convert(x), i, x])
  17. mapNum.sort()
  18. for i in range(n):
  19. nums[i]=mapNum[i][2]
  20. return nums

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章