ง่าย 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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก