2418.按身高排序
链接:2418.按身高排序
难度:Easy
标签:数组、哈希表、字符串、排序
简介:给你一个字符串数组 names ,和一个由 互不相同 的正整数组成的数组 heights 。两个数组的长度均为 n 。
题解 1 - python
- 编辑时间:2023-04-25
- 执行用时:56ms
- 内存消耗:15.4MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
    def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
        l = [i for i in range(len(names))]
        l.sort(key=lambda i: heights[i], reverse=True)
        return [names[i] for i in l]
题解 2 - cpp
- 编辑时间:2023-04-25
- 执行用时:32ms
- 内存消耗:19.8MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
    vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
        vector<int> idxs;
        for (int i = 0; i < names.size(); i++) idxs.push_back(i);
        sort(idxs.begin(), idxs.end(), [&](auto &i1, auto &i2) { return heights[i1] > heights[i2]; });
        vector<string> res;
        for (int i = 0; i < names.size(); i++) res.push_back(names[idxs[i]]);
        return res;
    }
};
题解 3 - typescript
- 编辑时间:2022-09-25
- 执行用时:76ms
- 内存消耗:45.9MB
- 编程语言:typescript
- 解法介绍:遍历。
function sortPeople(names: string[], heights: number[]): string[] {
  return new Array(names.length)
    .fill(0)
    .map((_, i) => i)
    .sort((a, b) => heights[b] - heights[a])
    .map(i => names[i]);
}
题解 4 - rust
- 编辑时间:2023-04-25
- 执行用时:8ms
- 内存消耗:2.2MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
    pub fn sort_people(names: Vec<String>, heights: Vec<i32>) -> Vec<String> {
        let mut l = (0..names.len()).collect::<Vec<usize>>();
        l.sort_by_key(|i| heights[*i]);        
        l.into_iter().rev().map(|i| names[i].clone()).collect()
    }
}