




Sponsored
Sponsored
This approach involves pairing each name with its corresponding height, sorting these pairs by height in descending order, and then extracting the sorted names. This makes use of the association between each name and its corresponding height.
Time Complexity: O(n log n) due to the sorting operation.
Space Complexity: O(n) for storing the list of tuples.
1import java.util.*;
2
3public class SortPeople {
4    public static String[] sortPeople(String[] names, int[] heights) {
5        int n = names.length;
6        Person[] people = new Person[n];
7        for (int i = 0; i < n; i++) {
8            people[i] = new Person(names[i], heights[i]);
9        }
10        Arrays.sort(people, (a, b) -> b.height - a.height);
11        String[] sortedNames = new String[n];
12        for (int i = 0; i < n; i++) {
13            sortedNames[i] = people[i].name;
14        }
15        return sortedNames;
16    }
17
18    static class Person {
19        String name;
20        int height;
21
22        Person(String name, int height) {
23            this.name = name;
24            this.height = height;
25        }
26    }
27}Create a class Person to hold the name and height together. Create an array of Person and sort it using a comparator that sorts by height in descending order. Finally, extract the sorted names.
Rather than pairing names and heights, you can directly sort the indices of the height array. After sorting the indices by descending heights, you can retrieve the names based on this sorted order of heights.
Time Complexity: O(n log n) due to sorting the indices.
Space Complexity: O(n) for auxiliary storage of indices.
1defThe code sorts indices based on the heights using negative heights to direct the sorting to descending order. After sorting, use these indices to create the sorted list of names.