Find the Middle Element
easySave
ArrayMath
Given an array of integers, return the middle element. If the array has an even number of elements, return the average of the two middle elements.
Example 1
Input
[ 1, 2, 3, 4, 5 ]
Output
3
Explanation. The middle element of an odd length array is simply the middle element.
Example 2
Input
[ 1, 2, 3, 4 ]
Output
2.5
Explanation. The array has an even number of elements, so the output is the average of the two middle elements, (2 + 3) / 2 = 2.5.
Example 3
Input
[ 10 ]
Output
10
Explanation. With only one element, that element is the middle by default.
Follow-up: How would you optimize your solution if multiple queries for different arrays are expected?
Constraints:
The array will contain at least one element. All elements are integers.
- Views
- 2