Tous les défis
Facile 0 résolus 0 % de réussite

Sort by a Chosen Key

Sort people by name or by age with a comparer chosen at run time, breaking ties consistently.

Ce que vous allez apprendre

  • Choose a sort order at run time
  • Break ties with a second key
  • Compare strings in ordinal order

Problème

Afficher la traduction

In C#, an IComparer<T> is an interface: any class that implements its Compare method can tell a sort which item comes first. Choosing a different comparer changes the order without changing the sort.

Sort the people by key:

  • name: by name (ordinal character order, so uppercase letters come before lowercase), and by age when names are equal.
  • age: by age, youngest first, and by name when ages are equal.

Implement sort_by_key(names, ages, key).

Input

names, ages: The people (same length).

key: "name" or "age".

Output

Return the names in sorted order.

Contraintes

0 ≤ number of people ≤ 100,000

0 ≤ age ≤ 150

Exemples

Exemple 1
Entrée :
key = "age"
ages = [30, 36, 30]
names = ["Lin", "Ada", "Bo"]

Sortie attendue :
expected = ["Bo", "Lin", "Ada"]
Entrée :
std::string key = "age";
std::vector<long long> ages = {30, 36, 30};
std::vector<std::string> names = {"Lin", "Ada", "Bo"};

Sortie attendue :
std::vector<std::string> expected = {"Bo", "Lin", "Ada"};
Entrée :
string key = "age";
long[] ages = new long[] {30, 36, 30};
string[] names = new string[] {"Lin", "Ada", "Bo"};

Sortie attendue :
string[] expected = new string[] {"Bo", "Lin", "Ada"};

Explication

Bo and Lin are both 30, so they are ordered by name before Ada (36): ["Bo", "Lin", "Ada"].

Exemple 2
Entrée :
key = "name"
ages = [30, 36, 30]
names = ["Lin", "Ada", "Bo"]

Sortie attendue :
expected = ["Ada", "Bo", "Lin"]
Entrée :
std::string key = "name";
std::vector<long long> ages = {30, 36, 30};
std::vector<std::string> names = {"Lin", "Ada", "Bo"};

Sortie attendue :
std::vector<std::string> expected = {"Ada", "Bo", "Lin"};
Entrée :
string key = "name";
long[] ages = new long[] {30, 36, 30};
string[] names = new string[] {"Lin", "Ada", "Bo"};

Sortie attendue :
string[] expected = new string[] {"Ada", "Bo", "Lin"};

Explication

Alphabetical order: ["Ada", "Bo", "Lin"].

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

Sort pairs of (name, age) instead of two separate lists.

Indice 2

The chosen key gives the main order; the other field breaks ties.

Indice 3

Use ordinal string comparison so uppercase sorts before lowercase.

Complexité attendue

O(n log n) time, O(n) extra space

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.