179. Largest Number

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]
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值