Problem overview
The function middleElement receives a vector of integers, nums, with an odd number of items, and returns the item in the middle. For [1, 2, 3] the answer is 2, and for [5, 9, 1, 8, 4] it is 1. The middle is about position, not size: 1 is the smallest number in the second vector, but it sits in the middle. A vector with one item, [7], returns that item.
Approach
With an odd number of items there is exactly one middle, and it has the same number of items on each side. The vector has indexes 0 to size - 1. For 5 items the indexes are 0 to 4, and the middle is index 2: two items come before it and two after.
The middle index is the size divided by 2, rounded down. In C++, dividing two integers with / already keeps only the whole part, so 5 / 2 is 2. No rounding function is needed.
Step by step
- Compute the middle index.
nums.size() / 2is the size divided by 2 with the fraction dropped. The lesson stores it in anintnamedmiddle. For 3 items it is 1, for 5 items it is 2, and for 1 item it is 0. - Return the item at that index.
nums[middle]is the middle number.
The solution in C++
class Solution {
public:
int middleElement(vector<int> &nums) {
int middle = nums.size() / 2;
return nums[middle];
}
};
The C++ details that matter:
- Integer division. When both sides of
/are integers, the result is an integer and the fraction is dropped. Herenums.size()is an integer type and2is anint, so no fraction appears. Dividing by2.0would give a floating-point number, such as 2.5 for a size of 5, which can't be used directly as an index. - The type of
size(). It returns an unsigned integer. Storing the result in anintconverts it back, which is safe for any vector that fits in memory with sizes this small. - Reference parameter.
vector<int> &numsavoids copying the vector. The function only reads from it. - No bounds check. The
[]operator doesn't check the index. A valid index is guaranteed here, because the vector has at least one item.
Edge cases and common mistakes
- Using
size() / 2 + 1. That is one index too far. For 5 items it would be index 3, not the middle. - Thinking of the middle as a value. The answer is the item at the middle position, not the median or the average. In
[5, 9, 1, 8, 4]the answer is 1, even though the numbers aren't sorted. - A single item.
1 / 2is 0, sonums[0]is returned. The same code handles it. - An even size. The lesson only gives odd sizes. For an even size such as 4,
4 / 2is 2, which picks the upper of the two middle items: for[1, 2, 3, 4]the code returns 3. - An empty vector. It has no middle, and
nums[0]on an empty vector is undefined behaviour. The constraints exclude it.
Testing
[1, 2, 3]gives 2.[5, 9, 1, 8, 4]gives 1.[7]gives 7.
