Input: names =["Mary","John","Emma"], heights =[180,165,170]Output: ["Mary","Emma","John"]Explanation: Mary is the tallest, followed by Emma and John.
Example 2:
1
2
3
Input: names =["Alice","Bob","Bob"], heights =[155,185,150]Output: ["Bob","Alice","Bob"]Explanation: The first Bob is the tallest, followed by Alice and the second Bob.
This is mainly about sorting, but arrays are separate, so lets see how we can sort the name and height pairs. Please look at the video explanation below:
publicclassSolution {
staticclassPerson {
String name;
int height;
Person(String name, int height) {
this.name= name;
this.height= height;
}
}
publicstatic String[]sortPeople(String[] names, int[] heights) {
int n = names.length;
Person[] people =new Person[n];
// Combine names and heightsfor (int i = 0; i < n; i++) {
people[i]=new Person(names[i], heights[i]);
}
// Sort the array of Person objects by height in descending order Arrays.sort(people, (a, b) -> b.height- a.height);
// Extract the names from the sorted Person array String[] sortedNames =new String[n];
for (int i = 0; i < n; i++) {
sortedNames[i]= people[i].name;
}
return sortedNames;
}
}
1
2
3
4
5
6
7
8
9
10
11
defsort_people(names, heights):
# Combine names and heights into a list of tuples people = list(zip(names, heights))
# Sort the list of tuples by height in descending order people.sort(key=lambda x: x[1], reverse=True)
# Extract the names from the sorted list of tuples sorted_names = [person[0] for person in people]
return sorted_names