簡単 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 つずつ開いてみましょう。

ヒント 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用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。