Dễ 1 người đã giải Tỷ lệ chấp nhận 100.0%

Median of a List

Find the middle value of a list after sorting.

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

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

Đề bài

Xem bản dịch

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.

Ràng buộc

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

Ví dụ

Ví dụ 1
Đầu vào:
numbers = [2, 8, 4, 10]

Kết quả mong đợi:
expected = 6.0
Đầu vào:
std::vector<long long> numbers = {2, 8, 4, 10};

Kết quả mong đợi:
double expected = 6.0;
Đầu vào:
long[] numbers = new long[] {2, 8, 4, 10};

Kết quả mong đợi:
double expected = 6.0;

Giải thích

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

Ví dụ 2
Đầu vào:
numbers = [9, 1, 4]

Kết quả mong đợi:
expected = 4.0
Đầu vào:
std::vector<long long> numbers = {9, 1, 4};

Kết quả mong đợi:
double expected = 4.0;
Đầu vào:
long[] numbers = new long[] {9, 1, 4};

Kết quả mong đợi:
double expected = 4.0;

Giải thích

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

Hướng tiếp cận

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

Gợi ý 1

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

Gợi ý 2

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

Gợi ý 3

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

Độ 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.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

# Người giải Ngôn ngữ Thời gian Bộ nhớ AI đánh giá Lời giải
1 RCRiccardo Corti Python 848 ms - 3/5 Xem code

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

Lời giải cộng đồng

Cảnh báo: Có 1 lời giải đầy đủ bên dưới Hãy thử tự giải trước. Bạn vẫn có thể xem code của người khác và nhận xét của AI. Đăng nhập và giải thử thách để tham gia thảo luận.