Problem
Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, upper], return its missing ranges.
Example:
1 |
|
Explanation
-
First check if the array is empty. If it’s empty, then check if
lower
andupper
the same. If the same, we return eitherlower
orupper
. Else we return the range fromlower
toupper
. -
Next, we check if
lower
is less than the first element of the array. If it is, then we check ifnums[0] - lower == 1
. If their difference is equal to 1, we returnlower
. Else, we return the range fromlower
tonums[0] - 1
. -
Next, loop from index
i
from 1 tonums.length()
exclusive. Compare the current elementnums[i]
with its previous elementnums[i-1]
. If the difference is greater than 1, or current element is greater than its previous element and their difference is less than 0, in the case of the difference is overflow[-2147483648, 2147483647]
. Then we check if the difference is equal to 2, then just addnums[i]-1
to the result list. Else we add the range of lower bound plus 1 to upper bound minus 1 to the result list, in other words,nums[i-1] + 1
tonums[i]-1
. -
Next, we check
upper
is greater than the last element of the array. Then, if their difference is 1, we just addupper
to the result list. Else, we add the range ofnums[nums.length-1] + 1
toupper
to the result list. At the end, return the result list.
Solution
1 |
|