S2 icon indicating copy to clipboard operation
S2 copied to clipboard

0179. Largest Number | LeetCode Cookbook

Open halfrost opened this issue 4 years ago • 5 comments

https://books.halfrost.com/leetcode/ChapterFour/0100~0199/0179.Largest-Number/

halfrost avatar Feb 16 '21 05:02 halfrost

...比如:“3” 和 “30” 比较,“30” 比 “3” 的字符序要大,这样...

3 的字符序不是比 30 大嗎?

wagaru avatar Aug 24 '21 01:08 wagaru

...比如:“3” 和 “30” 比较,“30” 比 “3” 的字符序要大,这样...

3 的字符序不是比 30 大嗎?

@wagaru (抱歉,回复你慢了。我这个月忙着搬家,现在搬到美国湾区了。)在 go 里面,30 比 3 字符大呢。

halfrost avatar Sep 15 '21 04:09 halfrost

啊…你的說對我誤會了

wagaru avatar Oct 03 '21 08:10 wagaru

啊…你的說對我誤會了

@wagaru 哈哈,没事没事,有啥问题直接提出来,一起讨论。

halfrost avatar Oct 03 '21 21:10 halfrost

借鉴了下思路,beat 100 100:

import (
    "bytes"
    "math"
    "sort"
    "strconv"
)

func largestNumber(nums []int) string {
    sort.Slice(nums, func(i, j int) bool {
        v1, v2 := float64(nums[i]), float64(nums[j])
        if v1 == v2 || v1 * v2 == 0 {
            return v2 < v1
        }
        lg1, lg2 := int(math.Log10(v1)), int(math.Log10(v2))
        return v2 * math.Pow10(lg1+1) + v1 < v1 * math.Pow10(lg2+1) + v2
    })
    var buf bytes.Buffer
    for _, num := range nums {
        if num == 0 && buf.Len() > 0 && buf.Bytes()[0] == '0' {
            continue
        }
        buf.WriteString(strconv.Itoa(num))
    }
    return buf.String()
}

hanlins avatar Nov 11 '21 02:11 hanlins