leetcode179最大数

leetcode179 Largest Number

Posted by BY on August 20, 2019

前言

一个多月没有更新了。

正文

问题来源

本问题来自leetcode上的179题。

问题描述

给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。

示例 1:

输入: [10,2]
输出: 210

示例 2:

输入: [3,30,34,5,9]
输出: 9534330

分析:

自己的代码

type stringSlice []string

func (s stringSlice) Len() int { return len(s) }
func (s stringSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s stringSlice) Less(i, j int) bool { 
    return strings.Compare(s[i]+s[j], s[j]+s[i]) > 0
}

func largestNumber(nums []int) string {
    strNums := make([]string, 0)
    for i := 0; i < len(nums); i++ {
        strNums = append(strNums, strconv.Itoa(nums[i]))
    }
    s := stringSlice(strNums)
    sort.Sort(s)
    ret := ""
    for i := 0; i < len(s); i++ {
        ret += s[i]
    }
    if ret[0] == '0' {
        return "0"
    }
    return ret
}

别人的代码

func largestNumber(nums []int) string {
    if len(nums) == 0 {
        return ""
    }
    ns := Nums(nums)
    sort.Sort(ns)
    ret := ""
    for i := len(nums)-1; i >= 0; i-- {
        ret = ret + strconv.Itoa(nums[i])
    }
    if ret[0] == '0' {
        return "0"
    }
    return ret
}

type Nums []int

func (n Nums) Len() int {
    return len(n)
}

func (n Nums) Less(a, b int) bool {
    na := n[a]
    nb := n[b]
    
    nab := strconv.Itoa(na) + strconv.Itoa(nb)
    nba := strconv.Itoa(nb) + strconv.Itoa(na)
    if nab > nba {
        return false
    }
    return true
} 

func (n Nums) Swap(a, b int) {
    n[a], n[b] = n[b], n[a]
    return
}

总结:

勤思考。

结语

不管怎么样好好加油。