Skip to content

Commit

Permalink
feat: add 2418
Browse files Browse the repository at this point in the history
  • Loading branch information
Joyee691 committed Jul 22, 2024
1 parent b1dd8e4 commit c78f031
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@
- [1721. Swapping Nodes in a Linked List(medium)](./book_sources/medium/1721.md)
- [2096. Step-By-Step Directions From a Binary Tree Node to Another(medium)](./book_sources/medium/2096.md)
- [2196. Create Binary Tree From Descriptions(medium)](./book_sources/medium/2196.md)
- [2418. Sort the People(easy)](./book_sources/easy/2418.md)
- [2751. Robot Collisions(hard)](./book_sources/hard/2751.md)

## 使用说明
Expand Down
1 change: 1 addition & 0 deletions book_sources/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,5 +125,6 @@
- [1721. Swapping Nodes in a Linked List(medium)](./medium/1721.md)
- [2096. Step-By-Step Directions From a Binary Tree Node to Another(medium)](./medium/2096.md)
- [2196. Create Binary Tree From Descriptions(medium)](./medium/2196.md)
- [2418. Sort the People(easy)](./easy/2418.md)
- [2751. Robot Collisions(hard)](./hard/2751.md)

3 changes: 2 additions & 1 deletion book_sources/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
- [1342. Number of Steps to Reduce a Number to Zero(easy)](./easy/1342.md)
- [1380. Lucky Numbers in a Matrix(easy)](./easy/1380.md)
- [1598. Crawler Log Folder(easy)](./easy/1598.md)
- [1710. Maximum Units on a Truck(medium)](./easy/1710.md)
- [1710. Maximum Units on a Truck(easy)](./easy/1710.md)
- [2418. Sort the People(easy)](./easy/2418.md)
- [Meduim](medium/README.md)
- [2. Add Two Numbers](./medium/2.md)
- [3. Longest Substring Without Repeating Characters(medium)](./medium/3.md)
Expand Down
38 changes: 38 additions & 0 deletions book_sources/easy/2418.md
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;
};
```

0 comments on commit c78f031

Please sign in to comment.