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
lowerandupperthe same. If the same, we return eitherlowerorupper. Else we return the range fromlowertoupper. -
Next, we check if
loweris 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 fromlowertonums[0] - 1. -
Next, loop from index
ifrom 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]-1to 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] + 1tonums[i]-1. -
Next, we check
upperis greater than the last element of the array. Then, if their difference is 1, we just addupperto the result list. Else, we add the range ofnums[nums.length-1] + 1toupperto the result list. At the end, return the result list.
Solution
1 | |