Go语言实现:【剑指offer】把数组排成最小的数

该题目来源于牛客网《剑指offer》专题。

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。

Go语言实现:

func printMinNumber(numbers []int) string {
   length := len(numbers)
   for i := 0; i < length-1; i++ {
      for j := i + 1; j < length; j++ {
         if compare(numbers[i], numbers[j]) {
            numbers[i], numbers[j] = numbers[j], numbers[i]
         }
      }
   }

   str := ""
   for _, v := range numbers {
      str += strconv.Itoa(v)
   }
   return str
}

func compare(a, b int) bool {
   //int to string
   m := strconv.Itoa(a) + strconv.Itoa(b)
   n := strconv.Itoa(b) + strconv.Itoa(a)
   //string to int
   mm, _ := strconv.Atoi(m)
   nn, _ := strconv.Atoi(n)
   if mm > nn {
      return true
   }
   return false
}
posted @ 2019-12-04 15:35  南方有嘉木1993  阅读(166)  评论(0编辑  收藏  举报