179. Largest Number
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: “210”
Example 2:
Input: [3,30,34,5,9]
Output: “9534330”
Note: The result may be very large, so you need to return a string instead of an integer.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/largest-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Think and method
This is an interesting sorting problem, and when I look at this problem, I think it’s a very simple problem, it just needs some sort of simple sorting, but when we think about the case in example 2.
If we had simply sorted them in descending order, the result would have been 95343303. I tried to make a lot of small changes in the code, but I couldn’t get the correct result. The official documentation showed me.
We should not treat it as a number, but as a string, and we need to compare the concatenated results when we sort every two numbers.To be specific, if we have two Numbers a and b, we can get the right sort by comparing the results of a-b> and b-a, (- means join), and if the comparison is wrong, there is an intermediate value c to consider.In this way, we will no longer have the above error situation.
Time complexity: O(nlogn)
mainly by sorting
Space complexity: O(n)
we use O(n) extra space to hold a copy of nums
Code:
func largestNumber(nums []int) string {
result := make([]string, len(nums))
number is converted to the corresponding string type
for i, num := range nums {
result[i] = strconv.Itoa(num)
}
//Custom sort:a-b > b-a - : means connect
sort.Slice(result, func(i, j int) bool {
return result[i]+result[j] > result[j]+result[i]
})
//special situation input[0,0]
if result[0] == "0" {
return "0"
}
//String concatenation
result_final := strings.Join(result, "")
return result_final
}
we need to consider the special situation :
input [0,0]
ideal ouput [0]
I made mistake at first with no judge.
The solution of this problem is relatively simple, so I have no other idea at present.But he is special and told me, when it comes to sorting, don’t model it and don’t always try to use all kinds of methods.Sometimes, you try to think in terms of a mathematical or problem solving reality.
Test:
Example 1:
Input: [10,2]
Example 2:
Input: [3,30,34,5,9]