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

Middle Item

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

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

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

โจทย์

ดูฉบับแปล

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.

เงื่อนไข

0 ≤ length of values ≤ 1000

−1000 ≤ each value ≤ 1000

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
values = [88, 72, 95, 60, 81, -1]

ผลลัพธ์ที่คาดหวัง:
expected = 95
อินพุต:
std::vector<long long> values = {88, 72, 95, 60, 81, -1};

ผลลัพธ์ที่คาดหวัง:
long long expected = 95;
อินพุต:
long[] values = new long[] {88, 72, 95, 60, 81, -1};

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

คำอธิบาย

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

ตัวอย่างที่ 2
อินพุต:
values = [10, 20, 30, 40, -5, 50]

ผลลัพธ์ที่คาดหวัง:
expected = 30
อินพุต:
std::vector<long long> values = {10, 20, 30, 40, -5, 50};

ผลลัพธ์ที่คาดหวัง:
long long expected = 30;
อินพุต:
long[] values = new long[] {10, 20, 30, 40, -5, 50};

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

คำอธิบาย

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

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

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

คำใบ้ 1

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

คำใบ้ 2

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

คำใบ้ 3

If nothing was copied, there is no middle item.

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

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

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

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

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

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

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

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