NOTE

Largest Number

Rearrange non-negative integers so their concatenation forms the largest integer.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Problem Description

Given a group of non-negative integers nums, rearrange the order of each number (each number cannot be split) so that they form the largest integer.

2. Approach

3. Implementation

func largestNumber(nums []int) string {
    strs := make([]string, 0, len(nums))
    for _, num := range nums {
        strs = append(strs, strconv.Itoa(num))
    }
    sort.Slice(strs, func(i, j int) bool {
        a := strs[i] + strs[j]
        b := strs[j] + strs[i]
        return a > b
    })
    if strs[0] == "0" {return "0"}
    var res string
    for _, str := range strs {
        res += str
    }
    return res
}

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub