Tutte le sfide
Facile 0 risolte 0% di accettazione

Sort by a Chosen Key

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

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

0 ≤ number of people ≤ 100,000

0 ≤ age ≤ 150

Esempi

Esempio 1
Input:
key = "age"
ages = [30, 36, 30]
names = ["Lin", "Ada", "Bo"]

Output atteso:
expected = ["Bo", "Lin", "Ada"]
Input:
std::string key = "age";
std::vector<long long> ages = {30, 36, 30};
std::vector<std::string> names = {"Lin", "Ada", "Bo"};

Output atteso:
std::vector<std::string> expected = {"Bo", "Lin", "Ada"};
Input:
string key = "age";
long[] ages = new long[] {30, 36, 30};
string[] names = new string[] {"Lin", "Ada", "Bo"};

Output atteso:
string[] expected = new string[] {"Bo", "Lin", "Ada"};

Spiegazione

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

Esempio 2
Input:
key = "name"
ages = [30, 36, 30]
names = ["Lin", "Ada", "Bo"]

Output atteso:
expected = ["Ada", "Bo", "Lin"]
Input:
std::string key = "name";
std::vector<long long> ages = {30, 36, 30};
std::vector<std::string> names = {"Lin", "Ada", "Bo"};

Output atteso:
std::vector<std::string> expected = {"Ada", "Bo", "Lin"};
Input:
string key = "name";
long[] ages = new long[] {30, 36, 30};
string[] names = new string[] {"Lin", "Ada", "Bo"};

Output atteso:
string[] expected = new string[] {"Ada", "Bo", "Lin"};

Spiegazione

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

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

Use ordinal string comparison so uppercase sorts before lowercase.

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.