Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9a33eff

Browse files
author
杨世超
committed
Update 剑指 Offer 45. 把数组排成最小的数.md
1 parent 74b1cdf commit 9a33eff

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

‎Solutions/剑指 Offer 45. 把数组排成最小的数.md

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,35 @@
55

66
## 题目大意
77

8-
给定一个非负整数数组 `nums`
8+
**描述**:给定一个非负整数数组 `nums`
99

10-
要求:将数组中的数字拼接起来排成一个数,打印能拼接出的所有数字中的最小的一个。
10+
**要求**:将数组中的数字拼接起来排成一个数,打印能拼接出的所有数字中的最小的一个。
11+
12+
**说明**:
13+
14+
- 0ドル < nums.length \le 100$。
15+
- 输出结果可能非常大,所以你需要返回一个字符串而不是整数。
16+
- 拼接起来的数字可能会有前导 `0`,最后结果不需要去掉前导 `0`
17+
18+
**示例**:
19+
20+
```Python
21+
输入 [3,30,34,5,9]
22+
输出 "3033459"
23+
```
1124

1225
## 解题思路
1326

14-
本质上是给数组进行排序。假设 `x``y` 是数组 `nums` 中的两个元素。如果拼接字符串 `x + y > y + x`,则 `x < y ``x` 应该排在 `y` 前面。反之,则 `x > y`
27+
### 思路 1:自定义排序
28+
29+
本质上是给数组进行排序。假设 `x``y` 是数组 `nums` 中的两个元素。则排序的判断规则如下所示:
30+
31+
- 如果拼接字符串 `x + y > y + x`,则 `x` 大于 `y `,`y` 应该排在 `x` 前面,从而使拼接起来的数字尽可能的小。
32+
- 反之,如果拼接字符串 `x + y < y + x`,则 `x` 小于 `y `,`x` 应该排在 `y` 前面,从而使拼接起来的数字尽可能的小。
1533

1634
按照上述规则,对原数组进行排序。这里使用了 `functools.cmp_to_key` 自定义排序函数。
1735

18-
##代码
36+
### 思路 1:自定义排序代码
1937

2038
```Python
2139
import functools
@@ -35,3 +53,6 @@ class Solution:
3553
return ''.join(nums_s)
3654
```
3755

56+
## 参考资料
57+
58+
- 【题解】[剑指 Offer 45. 把数组排成最小的数(自定义排序,清晰图解) - 把数组排成最小的数 - 力扣](https://leetcode.cn/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/solution/mian-shi-ti-45-ba-shu-zu-pai-cheng-zui-xiao-de-s-4/)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /