2418. Sort the People (22 July 2024)
Problem Description
Given two arrays:
- A string array
namescontaining the names of people, and - An integer array
heightscontaining the heights of these people.
Both arrays are of the same length, and each index corresponds to a person. Your task is to sort the people in descending order by their heights.
You can find the problem statement on LeetCode.
Solution Explanation
To solve this problem, we need to sort the names array based on the corresponding heights given in the heights array. Here's a step-by-step explanation of how we can achieve this:
1. Use a Map to Store Heights and Names
- We use a map where the key is the height, and the value is the corresponding name.
- By using a map with heights as keys and specifying
greater<int>for descending order, we can automatically sort the heights in descending order.
2. Iterate Through the Names and Heights
- Insert each name and corresponding height into the map.
3. Collect Sorted Results
- Extract the names from the map in order, which will give us the names sorted by heights in descending order.
Here's the C++ code implementing this solution:
class Solution {
public:
vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
// Map to store heights as keys and names as values, sorted in descending order
map<int, string, greater<int>> mp;
for (int i = 0; i < names.size(); i++) {
mp.insert({heights[i], names[i]});
}
// Vector to store the sorted names
vector<string> result;
for (auto elem : mp) {
result.push_back(elem.second);
}
return result;
}
};Initialization and Data Insertion
- Map (
mp):- Used to store heights and names, automatically sorting heights in descending order.
greater<int>ensures the keys are sorted in descending order.
Example
Consider the following inputs:
names = ["Alice", "Bob", "Charlie"]heights = [165, 180, 155]
Step-by-Step Execution
-
Insert each name and corresponding height into the map:
mpafter insertion:
{180: "Bob", 165: "Alice", 155: "Charlie"} -
Extract the names in sorted order from the map:
- Resulting order:
["Bob", "Alice", "Charlie"]
- Resulting order:
Conclusion
The described method uses a map to efficiently sort people by their heights in descending order. This approach leverages the automatic sorting feature of the map data structure to achieve the desired result with minimal code complexity.
This solution is efficient and easy to understand, making it a practical choice for solving the problem of sorting people by their heights.