classSolution: defminNumber(self, nums: List[int]) -> str: defquick_sort(l,r): if l >= r: return i, j = l, r
while i <j: # 从右向左找,strs[j] 小于 strs[l]的元素 while strs[j] + strs[l] >= strs[l] + strs[j] and i < j: j -= 1 # 从左向右找 strs[i] 大于 strs[l] 的元素 while strs[i] + strs[l] <= strs[l] + strs[i] and i < j: i += 1 strs[i],strs[l] = strs[l], strs[i] quick_sort(l,i-1) quick_sort(i+1,r) strs = [str(num) for num in nums] quick_sort(0,len(strs)-1)
return''.join(strs)
内置排序:
需定义排序规则:
Python 定义在函数 sort_rule(x, y) 中;
Java 定义为 (x, y) -> (x + y).compareTo(y + x) ;
C++ 定义为 (string& x, string& y){ return x + y < y + x; } ;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defminNumber(self, nums: List[int]) -> str: defsort_rule(x, y): a, b = x + y, y + x # 这里的加号代表 if a > b: return1 elif a < b: return -1 else: return0
strs = [str(num) for num in nums] strs.sort(key= functools.cmp_to_key(sort_rule)) return''.join(strs)