모든 챌린지
쉬움 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

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에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.