쉬움 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에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

아직 통과한 풀이가 없습니다. 풀어서 1위를 차지하세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.