Leetcode 2418. Sort the People
You are given an array of strings names
, where each names[i]
is the name of the i-th person. You are also given an array heights
, where each heights[i]
is the height of the i-th person.
Return names
sorted in descending order by the people’s heights.
names
and heights
?
names
corresponds to the person at the same index in heights
.Here is a Java implementation of the solution strategy:
import java.util.*;
public class SortPeopleByHeight {
public String[] sortPeople(String[] names, int[] heights) {
int n = names.length;
List<Pair> peopleList = new ArrayList<>();
for (int i = 0; i < n; i++) {
peopleList.add(new Pair(heights[i], names[i]));
}
// Sort the list by heights in descending order
peopleList.sort((a, b) -> b.height - a.height);
String[] sortedNames = new String[n];
for (int i = 0; i < n; i++) {
sortedNames[i] = peopleList.get(i).name;
}
return sortedNames;
}
class Pair {
int height;
String name;
Pair(int height, String name) {
this.height = height;
this.name = name;
}
}
// Example usage:
public static void main(String[] args) {
SortPeopleByHeight sorter = new SortPeopleByHeight();
String[] names = {"Mary", "John", "Emma"};
int[] heights = {180, 165, 170};
System.out.println(Arrays.toString(sorter.sortPeople(names, heights))); // Output: [Mary, Emma, John]
}
}
Thus, the overall time complexity of the solution is O(n log n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?