LeetCode 题解工作台
按身高排序
给你一个字符串数组 names ,和一个由 互不相同 的正整数组成的数组 heights 。两个数组的长度均为 n 。 对于每个下标 i , names[i] 和 heights[i] 表示第 i 个人的名字和身高。 请按身高 降序 顺序返回对应的名字数组 names 。 示例 1: 输入: nam…
4
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
根据题目描述,我们可以创建一个长度为 的下标数组 ,其中 。然后我们对 中的每个下标按照 中对应的身高降序排序,最后遍历排序后的 中的每个下标 ,将 加入答案数组即可。 我们也可以创建一个长度为 的数组 ,数组中每个元素是一个二元组 $(heights[i], i)$,然后我们对 按照身高降序排序。最后遍历排序后的 中的每个元素 $(heights[i], i)$,将 加入答案数…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个字符串数组 names ,和一个由 互不相同 的正整数组成的数组 heights 。两个数组的长度均为 n 。
对于每个下标 i,names[i] 和 heights[i] 表示第 i 个人的名字和身高。
请按身高 降序 顺序返回对应的名字数组 names 。
示例 1:
输入:names = ["Mary","John","Emma"], heights = [180,165,170] 输出:["Mary","Emma","John"] 解释:Mary 最高,接着是 Emma 和 John 。
示例 2:
输入:names = ["Alice","Bob","Bob"], heights = [155,185,150] 输出:["Bob","Alice","Bob"] 解释:第一个 Bob 最高,然后是 Alice 和第二个 Bob 。
提示:
n == names.length == heights.length1 <= n <= 1031 <= names[i].length <= 201 <= heights[i] <= 105names[i]由大小写英文字母组成heights中的所有值互不相同
解题思路
方法一:排序
根据题目描述,我们可以创建一个长度为 的下标数组 ,其中 。然后我们对 中的每个下标按照 中对应的身高降序排序,最后遍历排序后的 中的每个下标 ,将 加入答案数组即可。
我们也可以创建一个长度为 的数组 ,数组中每个元素是一个二元组 ,然后我们对 按照身高降序排序。最后遍历排序后的 中的每个元素 ,将 加入答案数组即可。
时间复杂度 ,空间复杂度 。其中 是数组 和 的长度。
class Solution:
def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
idx = list(range(len(heights)))
idx.sort(key=lambda i: -heights[i])
return [names[i] for i in idx]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n \cdot \log n) due to the sorting of n elements. Space complexity is O(n) because we create an auxiliary array of tuples pairing names and heights. |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Expect a direct mapping of names to heights and correct descending sort order.
- question_mark
Be prepared to explain why a hash or tuple-based approach avoids mixing names and heights.
- question_mark
Highlight the pattern of scanning arrays and using auxiliary structures for sorting without losing associations.
常见陷阱
外企场景- error
Sorting names and heights separately without pairing can misalign names with heights.
- error
Assuming heights are not distinct and trying to handle duplicates unnecessarily.
- error
Forgetting to return only names in the final output instead of height-name pairs.
进阶变体
外企场景- arrow_right_alt
Sort by other attributes such as weight or age while keeping name mapping intact.
- arrow_right_alt
Handle duplicate heights by breaking ties alphabetically or by original index.
- arrow_right_alt
Sort names in ascending height order instead of descending.