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

[pull] main from itcharge:main #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
pull merged 6 commits into AlgorithmAndLeetCode:main from itcharge:main
Jun 10, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Update 剑指 Offer 45. 把数组排成最小的数.md
  • Loading branch information
杨世超 committed Jun 10, 2022
commit 9a33eff6543702e4ff6a860ad3f9638f2d268707
29 changes: 25 additions & 4 deletions Solutions/剑指 Offer 45. 把数组排成最小的数.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,35 @@

## 题目大意

给定一个非负整数数组 `nums`。
**描述**:给定一个非负整数数组 `nums`。

要求:将数组中的数字拼接起来排成一个数,打印能拼接出的所有数字中的最小的一个。
**要求**:将数组中的数字拼接起来排成一个数,打印能拼接出的所有数字中的最小的一个。

**说明**:

- 0ドル < nums.length \le 100$。
- 输出结果可能非常大,所以你需要返回一个字符串而不是整数。
- 拼接起来的数字可能会有前导 `0`,最后结果不需要去掉前导 `0`。

**示例**:

```Python
输入 [3,30,34,5,9]
输出 "3033459"
```

## 解题思路

本质上是给数组进行排序。假设 `x`、`y` 是数组 `nums` 中的两个元素。如果拼接字符串 `x + y > y + x`,则 `x < y `。`x` 应该排在 `y` 前面。反之,则 `x > y`。
### 思路 1:自定义排序

本质上是给数组进行排序。假设 `x`、`y` 是数组 `nums` 中的两个元素。则排序的判断规则如下所示:

- 如果拼接字符串 `x + y > y + x`,则 `x` 大于 `y `,`y` 应该排在 `x` 前面,从而使拼接起来的数字尽可能的小。
- 反之,如果拼接字符串 `x + y < y + x`,则 `x` 小于 `y `,`x` 应该排在 `y` 前面,从而使拼接起来的数字尽可能的小。

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

## 代码
### 思路 1:自定义排序代码

```Python
import functools
Expand All @@ -35,3 +53,6 @@ class Solution:
return ''.join(nums_s)
```

## 参考资料

- 【题解】[剑指 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/)

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