leetcode#179 Largest Number

在這裏插入圖片描述
將整數轉換爲字符串,然後排序即可(需自定義排序規則爲: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
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章