Problem: 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:
Input: names = ["Mary","John","Emma"], heights = [180,165,170] Output: ["Mary","Emma","John"] Explanation: Mary is the tallest, followed by Emma and John.
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.
Approach: This a simple problem of sorting using a custom comparator. You can directly look at the implementation to understand the problem.
Implementation in C#:
public class People
{
public string Name {get; set;}
public int Height {get; set;}
public People(string name, int height)
{
this.Name = name;
this.Height = height;
}
}
public class Solution
{
public string[] SortPeople(string[] names, int[] heights)
{
int length = names?.Length ?? 0;
if (length == 0)
{
return new string[] {};
}
People[] people = new People[length];
for (int i = 0; i < length; ++i)
{
people[i] = new People(names[i], heights[i]);
}
Array.Sort(people, (p1, p2) => {
return p2.Height.CompareTo(p1.Height);
});
return people.Select(p => p.Name).ToArray();
}
}
Complexity: O(nlogn)
No comments:
Post a Comment