2418. Sort the People
Easy
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 ith
person.
Return names
sorted in descending order by the people's heights.
Example 1:
- 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:
- 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.
Constraints:
n == names.length == heights.length
1 <= n <= 103
1 <= names[i].length <= 20
1 <= heights[i] <= 105
-
names[i]
consists of lower and upper case English letters. - All the values of
heights
are distinct.
Hint:
- Find the tallest person and swap with the first person, then find the second tallest person and swap with the second person, etc. Repeat until you fix all n people.
Solution:
To solve this problem, we can follow these steps:
- Combine Names and Heights: Create a combined array of pairs where each pair consists of a name and its corresponding height.
- Sort the Combined Array: Sort the combined array based on heights in descending order.
- Extract Sorted Names: Extract the names from the sorted combined array.
Let's implement this solution in PHP: 2418. Sort the People
<?php
// Example usage:
$names = ["Mary","John","Emma"];
$heights = [180,165,170];
$result = sortPeople($names, $heights);
echo implode(",", $result); // Output: Mary,Emma,John
?>
Explanation:
-
Combining Names and Heights:
- We create an array called
$combined
where each element is a pair of a name and its corresponding height. - This is done using a loop that iterates through the indices of the
names
andheights
arrays.
- We create an array called
-
Sorting:
- We use the
usort
function to sort the$combined
array. - The sorting is based on the heights (the second element of each pair) in descending order. The comparison function returns the difference between the heights to achieve this.
- We use the
-
Extracting Sorted Names:
- After sorting, we extract the names from the
$combined
array into the$sortedNames
array. - This is done using another loop that goes through the sorted pairs.
- After sorting, we extract the names from the
This approach ensures that the names are returned in the order of descending heights, as required. The time complexity is (O(n \log n)) due to the sorting step, which is efficient for the input size constraints.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
Top comments (0)