日期: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)
C++ 程式碼
使用時間約為 4 ms,記憶體約為 264 kB,通過測試。
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
while(scanf("%d", &n) != EOF) {
vector<int> arr (n);
for(int i=0; i<n; i++) scanf("%d", &arr[i]);
sort(arr.begin(), arr.end(), [](int a, int b) {
if (a%10 == b%10) return a > b;
return a%10 < b%10; } );
for(int i=0; i<n-1; i++) printf("%d ", arr[i]);
printf("%d\n", arr[n-1]);
}
return 0;
}
沒有留言:
張貼留言