Find Middle Element
Given a non-empty array of integers, return the middle element of the array. If the array has an even number of elements, return the right side of the two middle elements.
[ 1, 2, 3 ]
Explanation. The middle index of an array of size 3 is 1. The value at index 1 is 2.
[ 1, 2, 3, 4 ]
Explanation. For an even length array of size 4, the middle elements are at indices 1 and 2. This function returns the element on the right, which is at index 2 and the value is 3.
[ 5 ]
Explanation. With a single element, that element is naturally the middle, at index 0.
[ 7, 8, 9, 10, 11, 12, 13, 14 ]
Explanation. The array has 8 elements, with the middle indices being 3 and 4. The function selects the right middle, which is at index 4 with the value 11.
Follow-up: Can you solve this problem in O(1) time complexity?
The input array will not be empty and will contain at least one integer.
- Views
- 3