Dễ 0 đã giải Tỷ lệ chấp nhận 0%

Sort by a Chosen Key

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

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

0 ≤ number of people ≤ 100,000

0 ≤ age ≤ 150

Ví dụ

Ví dụ 1
Đầu vào:
key = "age"
ages = [30, 36, 30]
names = ["Lin", "Ada", "Bo"]

Kết quả mong đợi:
expected = ["Bo", "Lin", "Ada"]
Đầu vào:
std::string key = "age";
std::vector<long long> ages = {30, 36, 30};
std::vector<std::string> names = {"Lin", "Ada", "Bo"};

Kết quả mong đợi:
std::vector<std::string> expected = {"Bo", "Lin", "Ada"};
Đầu vào:
string key = "age";
long[] ages = new long[] {30, 36, 30};
string[] names = new string[] {"Lin", "Ada", "Bo"};

Kết quả mong đợi:
string[] expected = new string[] {"Bo", "Lin", "Ada"};

Giải thích

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

Ví dụ 2
Đầu vào:
key = "name"
ages = [30, 36, 30]
names = ["Lin", "Ada", "Bo"]

Kết quả mong đợi:
expected = ["Ada", "Bo", "Lin"]
Đầu vào:
std::string key = "name";
std::vector<long long> ages = {30, 36, 30};
std::vector<std::string> names = {"Lin", "Ada", "Bo"};

Kết quả mong đợi:
std::vector<std::string> expected = {"Ada", "Bo", "Lin"};
Đầu vào:
string key = "name";
long[] ages = new long[] {30, 36, 30};
string[] names = new string[] {"Lin", "Ada", "Bo"};

Kết quả mong đợi:
string[] expected = new string[] {"Ada", "Bo", "Lin"};

Giải thích

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

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

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

Gợi ý 2

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

Gợi ý 3

Use ordinal string comparison so uppercase sorts before lowercase.

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.