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

Middle Item

Read numbers up to a negative sentinel and return the middle one.

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

  • Stop reading input at a sentinel value
  • Find the middle index of a list
  • Handle an empty input

Đề bài

Xem bản dịch

A teacher types quiz scores into a program and ends the list with any negative number, which is a stop signal and not a score. The program should report the middle score in the order the scores were typed (they are not sorted). With k scores the middle one is at position k / 2 counting from 0 and rounding down, so for an even count it is the second of the two middle scores.

Implement middle_item(values).

Input

values: The numbers as typed. Reading stops at the first negative number; it and everything after it are ignored. If there is no negative number, every value is a score.

Output

Return the middle score. If there are no scores before the stop signal, return -1.

Ràng buộc

0 ≤ length of values ≤ 1000

−1000 ≤ each value ≤ 1000

Ví dụ

Ví dụ 1
Đầu vào:
values = [88, 72, 95, 60, 81, -1]

Kết quả mong đợi:
expected = 95
Đầu vào:
std::vector<long long> values = {88, 72, 95, 60, 81, -1};

Kết quả mong đợi:
long long expected = 95;
Đầu vào:
long[] values = new long[] {88, 72, 95, 60, 81, -1};

Kết quả mong đợi:
long expected = 95;

Giải thích

The scores are 88, 72, 95, 60, 81; there are 5, so the middle is position 2, which is 95.

Ví dụ 2
Đầu vào:
values = [10, 20, 30, 40, -5, 50]

Kết quả mong đợi:
expected = 30
Đầu vào:
std::vector<long long> values = {10, 20, 30, 40, -5, 50};

Kết quả mong đợi:
long long expected = 30;
Đầu vào:
long[] values = new long[] {10, 20, 30, 40, -5, 50};

Kết quả mong đợi:
long expected = 30;

Giải thích

Reading stops at −5, leaving 4 scores; position 2 holds 30.

Hướng tiếp cận

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

Gợi ý 1

Copy values into a new list until you meet the first negative number.

Gợi ý 2

With k items the middle index is k / 2 using integer division.

Gợi ý 3

If nothing was copied, there is no middle item.

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

O(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.

Chưa có lời giải nào đạt. Giải bài này để giành hạng nhất.

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.