2024-09-18|閱讀時間 ‧ 約 22 分鐘

179. Largest Number

Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.

Since the result may be very large, so you need to return a string instead of an integer.

 

Example 1:

Input: nums = [10,2]
Output: "210"

Example 2:

Input: nums = [3,30,34,5,9]
Output: "9534330"

 

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 109

解法

先建立一個陣列,把數字都轉換成字串存入,然後就字串陣列進行降序排序,把最後字串陣列的內容組合便是答案

Golang

func largestNumber(nums []int) string {

    ans := make([]string, len(nums))

    for i, v :=range nums {

        ans[i] = strconv.Itoa(v)

    }

    sort.Slice(ans, func(i, j int) bool {

        return ans[i] + ans[j] > ans[j]+ ans[i]

    })

    if ans[0] == "0" {

        return "0"

    }

    return strings.Join(ans,"")

}

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.