將整數轉換爲字符串,然後排序即可(需自定義排序規則爲:s1 + s2 > s2 + s1)
import "strconv"
type newType []string
func (p newType) Len() int {
return len(p)
}
// 排序規則
func (p newType) Less(i, j int) bool {
return p[i] + p[j] > p[j] + p[i]
}
func (p newType) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
func largestNumber(nums []int) string {
ns := make([]string, len(nums))
for k, v := range nums{
ns[k] = strconv.FormatInt(int64(v), 10)
}
sort.Sort(newType(ns))
res := ""
for _, v := range ns{
if len(res) == 0 && v == "0"{
continue
}
res += v
}
if len(res) == 0{
return "0"
}
return res
}