Problem overview
The method middleElement receives an ArrayBuffer[Int] named nums with an odd number of items and returns the item in the middle. For [1, 2, 3] the answer 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.
Approach
The middle index is the number of items divided by 2, rounded down. With 5 items the indexes run from 0 to 4, and 5 divided by 2, rounded down, is 2: two items come before index 2 and two come after it. With 1 item the middle index is 0, and the only item is the middle one.
Scala makes the rounding easy. Dividing one Int by another with / keeps only the whole part, so 5 / 2 is 2, not 2.5. The size of an ArrayBuffer is an Int too, so nums.size / 2 is already the middle index.
Step by step
- Find the middle index. Store
nums.size / 2in avalnamedmiddle. - Return the item at that index with
nums(middle).
The solution in Scala
class Solution {
def middleElement(nums: ArrayBuffer[Int]): Int = {
val middle = nums.size / 2
return nums(middle)
}
}
A few Scala details:
- Integer division truncates. For the non-negative sizes used here, that is the same as rounding down.
- An
ArrayBufferreads an item with parentheses,nums(middle), like anArraydoes. Its length isnums.size, andnums.lengthgives the same number. - Splitting the work into two lines, with the index in a named
val, makes the code easy to read and to check while you debug.nums(nums.size / 2)in one line is equivalent. - The type
ArrayBufferlives inscala.collection.mutable. In a file of your own, addimport scala.collection.mutable.ArrayBufferto use it.
Tracing an example
For [5, 9, 1, 8, 4], nums.size is 5 and middle is 5 / 2 = 2. The item at index 2 is 1, which is the result. For [1, 2, 3], middle is 1 and the item at index 1 is 2. For [7], middle is 0, and nums(0) is 7.
The same formula picks the position for every odd size: 7 items give index 3, and 9 items give index 4. In each case there are as many items before the middle as after it.
Edge cases and common mistakes
- Returning the middle index. The method returns the item at that index, not the index itself. In
[5, 9, 1, 8, 4]the index is 2 and the answer is 1. - Using
nums.size / 2 - 1. That is one place too far left. With 3 items it gives index 0, which is the first item rather than the middle one. - Rounding up. Division of
Intvalues rounds down. The lesson's rule is the same. - Even sizes. The lesson only gives odd sizes. For an even size such as 4 items,
nums.size / 2is 2, the upper of the two middle items, in a buffer with no single middle. - An empty buffer. Index 0 doesn't exist, so
nums(0)would throw an exception. The lesson never passes one.
Testing
[1, 2, 3]gives 2.[5, 9, 1, 8, 4]gives 1.[7]gives 7.
