NOTE
Arrange an Array into the Smallest Number
Mirror translation of the original Sword Offer note: Arrange an Array into the Smallest Number.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Problem Description
Given an array of positive integers, concatenate all numbers to form one number and print the smallest possible result. For example, for {3,32,321}, the smallest number that can be formed is 321323.
2. Approach
- Custom string ordering
3. Implementation
package main
import (
"sort"
"strconv"
)
/**
* The class name, method name, and parameter names in the code have already been specified. Do not modify them; directly return the value required by the method.
*
* @param numbers one-dimensional int array
* @return string
*/
// Time complexity: O(NlogN), using sorting
// Space complexity: O(1)
func PrintMinNumber(numbers []int) string {
sort.Slice(numbers, func(i, j int) bool {
a, b := strconv.Itoa(numbers[i]), strconv.Itoa(numbers[j])
return a+b < b+a
})
res := ""
for _, number := range numbers {
res += strconv.Itoa(number)
}
return res
}
func minNumber(nums []int) string {
strs := make([]string, 0 , len(nums))
for _, num := range nums {
str := strconv.Itoa(num)
strs = append(strs, str)
}
sort.Slice(strs, func(i,j int) bool {
a := strs[i]+ strs[j]
b := strs[j]+ strs[i]
return a < b
})
res := ""
for _, str := range strs{
res += str
}
return res
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub