समस्या
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
उदाहरण
इनपुट:
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.
इनपुट:
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 के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।