Problem overview
The function middle_element takes a vector of integers, nums, with an odd number of items, and returns the item in the middle. Every number is between -1000 and 1000.
For [1, 2, 3] the result is 2. For [5, 9, 1, 8, 4] it is 1: the middle is about the position, not the size of the number. For [7] it is 7, because the only item is the middle one.
Approach
With an odd number of items, the middle one has the same number of items on each side. Five items have the indexes 0 to 4, and the middle index is 2: two items come before it and two after it. In general the middle index is the length divided by 2, rounded down.
Rust does that rounding for you. Dividing two integers with / keeps only the whole part, so 5 / 2 is 2, and 1 / 2 is 0. The length of a vector, nums.len(), is a usize, and so is the result of the division, which is exactly the type an index needs.
Step by step
- Compute the middle index as
nums.len() / 2and store it inmiddlewithlet. - Return the item at that index as the last expression, with no semicolon.
The solution in Rust
impl Solution {
fn middle_element(nums: Vec<i32>) -> i32 {
let middle = nums.len() / 2;
nums[middle]
}
}
Some details worth knowing:
- Integer division.
/on integers drops the fractional part, so there is no need for a separate rounding step. Dividing by 2 is the same as asking for "half, rounded down". usizeas the index type. A vector is indexed with ausize. Becauselen()already returns one,middleneeds no conversion.- The last expression is the result.
nums[middle]has no semicolon, so its value, ani32, is returned. The number is copied out of the vector, so nothing is moved. - One item. The length is 1,
1 / 2is 0, and the item at index 0 is the middle one. - The empty vector panics. Its length is 0, so the index is 0, and reading an item that isn't there stops the program with an "index out of bounds" message. The lesson always gives at least one item.
Edge cases and common mistakes
- Using
len() / 2 + 1. Counting from 1 instead of 0 gives the item after the middle:[1, 2, 3]would return 3. - Even lengths. The lesson doesn't use them, since an even number of items has no single middle.
nums.len() / 2would return the second of the two central items: for[1, 2, 3, 4]it returns 3. - Returning the middle index instead of the item. For
[5, 9, 1, 8, 4], the index is 2 but the answer is 1. - Looking for the middle value. The task is about position. The middle item is not the median and isn't the number in the middle of the sorted order.
Testing
[1, 2, 3]gives2.[5, 9, 1, 8, 4]gives1.[7]gives7.
