-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
42 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
# 2418. Sort the People | ||
|
||
> [Leetcode link](https://leetcode.com/problems/sort-the-people/) | ||
## 题目简介 | ||
|
||
题目给了我们两个数组 `names`, `heights` 要求我们把人物的名字根据身高排序 | ||
|
||
## 解题思路 | ||
|
||
这是一个简单题,关键的卡点在于我们要怎么在排序的时候维持两个数组元素的一致性 | ||
|
||
在 js 中,我们可以简单的用一个 map 来保存两者的映射关系,这样只要我们把 `heights` 排序好之后根据映射关系以此找回 `names` 就好 | ||
|
||
### Javascript | ||
|
||
```js | ||
/** | ||
* @param {string[]} names | ||
* @param {number[]} heights | ||
* @return {string[]} | ||
*/ | ||
var sortPeople = function(names, heights) { | ||
const map = {}; | ||
// 建立映射关系 | ||
names.forEach((item, index) => { | ||
map[heights[index]] = item; | ||
}) | ||
// 排序 | ||
heights.sort((a, b) => b-a); | ||
// 根据映射关系取回名字 | ||
heights.forEach((item, index) => { | ||
names[index] = map[item]; | ||
}) | ||
return names; | ||
}; | ||
``` | ||
|