Find Middle Element
easySave
ArrayMath
Given a non-empty array of integers, find the middle element of the array. 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 the array [1, 2, 3, 4, 5] is 3.
Example 2
Input
[ 1, 2, 3, 4, 5, 6 ]
Output
3.5
Explanation. The two middle elements are 3 and 4. The average is (3 + 4) / 2 = 3.5.
Example 3
Input
[ 10 ]
Output
10
Explanation. The array has only one element, so the middle element is 10.
Follow-up: How would you modify your solution if the input data type changes to a linked list instead of an array?
Constraints:
The input array will not be empty and will contain at least one element. All elements will be integers.
- Views
- 3