2418. 按身高排序
难度:中等
题目:
给你一个字符串数组 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.length
1 <= n <= 103
1 <= names[i].length <= 20
1 <= heights[i] <= 105
names[i]
由大小写英文字母组成heights
中的所有值互不相同
个人思路
思路与算法
解法一 排序
我们可以将 和 绑定为一个二元组,然后对所有的二元组按照 排序。最后取出其中的 即为答案。
除了以上方法,我们还可以创建一个索引数组 ,其中 。排序完成后,对于所有的 都有 。然后我们遍历 从 到 ,将 追加到答案数组中。
代码
class Solution {
public:
vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
int n = names.size();
vector<int> indices(n);
iota(indices.begin(), indices.end(), 0);
sort(indices.begin(), indices.end(), [&](int x, int y) {
return heights[x] > heights[y];
});
vector<string> res(n);
for (int i = 0; i < n; i++) {
res[i] = names[indices[i]];
}
return res;
}
};
class Solution {
public:
vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
int n = names.size();
vector<pair<int, int>> arr;
for (int i = 0; i < n; ++i) {
arr.emplace_back(-heights[i], i);
}
sort(arr.begin(), arr.end());
vector<string> ans;
for (int i = 0; i < n; ++i) {
ans.emplace_back(names[arr[i].second]);
}
return ans;
}
};
class Solution {
public:
vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
unordered_map<int, int> elements;
vector<string> ans;
for(int i = 0; i < heights.size(); i++){
int height = heights[i];
elements[height] = i;
}
sort(heights.rbegin(), heights.rend());
for(int j = 0; j < heights.size(); j++){
int name = elements[heights[j]];
ans.push_back(names[name]);
}
return ans;
}
};
每天记录一下做题思路。