You are given an array of strings names
, and an array heights
that consists of distinct positive integers. Both arrays are of length n
.
For each index i
, names[i]
and heights[i]
denote the name and height of the i<sup>th</sup>
person.
Return names
sorted in descending order by the people's heights.
LeetCode Problem - 2418
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
class Solution {
// Method to sort people by their heights
public String[] sortPeople(String[] names, int[] heights) {
// Create a HashMap to store height as key and name as value
Map<Integer, String> map = new HashMap<>();
// Populate the HashMap with heights and corresponding names
for (int i = 0; i < heights.length; i++) {
map.put(heights[i], names[i]);
}
// Sort the heights array
Arrays.sort(heights);
// Create a result array to store sorted names
String[] resultArr = new String[heights.length];
// Traverse the sorted heights array in reverse order
for (int z = 0, i = heights.length - 1; i >= 0; i--) {
// Retrieve the name corresponding to the current height
resultArr[i] = map.get(heights[z]);
// Increment the index to get the next name
z++;
}
// Return the sorted array of names
return resultArr;
}
}