Given an ordered integer array nums
with no duplicate elements.
Return a list of the smallest ordered range intervals that exactly cover all the numbers in the array. In other words, each element of nums
is exactly covered by a certain interval range, and there are no numbers x
that belong to a certain range but do not belong to nums
.
Each interval range [a, b]
in the list should be output in the following format:
"a->b"
, if a != b
."a"
, if a == b
.In this problem, it is especially important to pay attention to the case when two values are equal. Only one value needs to be placed. Below the solution is my previous approach, using an increasing sequence value for comparison with the original sequence value, it needs special handling when two values are equal. The new approach is simpler, using two pointers. If the difference is one, the right pointer moves forward by one. If the difference is greater than one, push an interval into the array, then move both left and right pointers to the next value. First, define the array length. Then, if the length is 0
, return directly. If the length is 1
, return the value and convert it to a string. Then define the left and right pointers, and define a target array. Establish a loop. In Js
, there is no need to worry too much about out-of-bounds situations. When comparing later, it only needs to be treated as undefined
. Define the current value and the previous value. If the difference between these two values is 1
, then move the right pointer. If the two pointers are equal, convert one of the values to a string and push it into the target array, and set both pointers to the current value. If the difference is not 1
and they are not equal, then push the concatenated string into the array and set both pointers to the current value. After the loop, return the target array.