ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Median of a List

Find the middle value of a list after sorting.

สิ่งที่คุณจะได้เรียนรู้

  • Sort a list and find its middle
  • Handle even and odd lengths
  • Average the two middle values

โจทย์

ดูฉบับแปล

Sort the values into ascending order. For an odd number of values, take the middle one. For an even number, take the arithmetic mean of the two middle values. This challenge accepts only nonempty lists.

Implement median_number(numbers).

Input

numbers: The nonempty list of values.

Output

Return the median as a number; it may end in .5.

เงื่อนไข

1 ≤ list length ≤ 100,000. Each value is an integer between −1,000,000,000 and 1,000,000,000.

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
numbers = [2, 8, 4, 10]

ผลลัพธ์ที่คาดหวัง:
expected = 6.0
อินพุต:
std::vector<long long> numbers = {2, 8, 4, 10};

ผลลัพธ์ที่คาดหวัง:
double expected = 6.0;
อินพุต:
long[] numbers = new long[] {2, 8, 4, 10};

ผลลัพธ์ที่คาดหวัง:
double expected = 6.0;

คำอธิบาย

Sorted order is 2, 4, 8, 10. The middle pair averages to (4 + 8) / 2 = 6.

ตัวอย่างที่ 2
อินพุต:
numbers = [9, 1, 4]

ผลลัพธ์ที่คาดหวัง:
expected = 4.0
อินพุต:
std::vector<long long> numbers = {9, 1, 4};

ผลลัพธ์ที่คาดหวัง:
double expected = 4.0;
อินพุต:
long[] numbers = new long[] {9, 1, 4};

ผลลัพธ์ที่คาดหวัง:
double expected = 4.0;

คำอธิบาย

Sorted order is 1, 4, 9, whose middle value is 4.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

The median depends on sorted order, so the positions in the sorted list are what matter.

คำใบ้ 2

After sorting, use the middle element for odd length, or combine the two middle elements for even length.

คำใบ้ 3

Be careful to preserve halves when averaging two middle values, since the answer may end in .5.

ความซับซ้อนที่คาดหวัง

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

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

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

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

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