日期:2025年7月4日
ZeroJudge 題目連結:a225. 明明愛排列
解題想法
這題在 Python 可以用內建的排序工具 sort,搭配 functools.cmp_to_key 與自訂比較式;在 C++ 可以用 algorithm 函式庫的 sort,搭配 lambda function 自訂比較式,寫起來會快很多。
Python 程式碼
使用時間約為 50 ms,記憶體約為 4.2 MB,通過測試。
import sys
from functools import cmp_to_key
def mycmp(a, b):
if a%10 == b%10:
if a > b: return -1
elif a < b: return 1
else: return 0
elif a%10 < b%10: return -1
else: return 1
for line in sys.stdin:
n = int(line)
arr = list(map(int, sys.stdin.readline().split()))
arr.sort(key = cmp_to_key(mycmp))
print(*arr)