簡単 0件解決済み 正答率0%

Sort by a Chosen Key

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

このチャレンジで学べること

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

問題

翻訳を表示

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.

制約

0 ≤ number of people ≤ 100,000

0 ≤ age ≤ 150

例

例 1
入力:
key = "age"
ages = [30, 36, 30]
names = ["Lin", "Ada", "Bo"]

期待される出力:
expected = ["Bo", "Lin", "Ada"]
入力:
std::string key = "age";
std::vector<long long> ages = {30, 36, 30};
std::vector<std::string> names = {"Lin", "Ada", "Bo"};

期待される出力:
std::vector<std::string> expected = {"Bo", "Lin", "Ada"};
入力:
string key = "age";
long[] ages = new long[] {30, 36, 30};
string[] names = new string[] {"Lin", "Ada", "Bo"};

期待される出力:
string[] expected = new string[] {"Bo", "Lin", "Ada"};

解説

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

例 2
入力:
key = "name"
ages = [30, 36, 30]
names = ["Lin", "Ada", "Bo"]

期待される出力:
expected = ["Ada", "Bo", "Lin"]
入力:
std::string key = "name";
std::vector<long long> ages = {30, 36, 30};
std::vector<std::string> names = {"Lin", "Ada", "Bo"};

期待される出力:
std::vector<std::string> expected = {"Ada", "Bo", "Lin"};
入力:
string key = "name";
long[] ages = new long[] {30, 36, 30};
string[] names = new string[] {"Lin", "Ada", "Bo"};

期待される出力:
string[] expected = new string[] {"Ada", "Bo", "Lin"};

解説

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

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

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

ヒント 2

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

ヒント 3

Use ordinal string comparison so uppercase sorts before lowercase.

目安の計算量

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

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。