Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Before solving it, let’s assume first we have got a pair list like this:
'((0 1) (3 4) (5 6) (8 8) (10 10))
If we apply a formatter function to it:
if start and end are the same, just transform this number to string;
otherwise transfer a range ‘(start end) to a string: “start->end”.
This list will just turn it '("0->1" "3->4" "5->6" "8" "10") as expected.
The procedure below implements the specification above:
Now, the question is getting easier, we meet a task to turn list
(0 1 3 4 6 8 10) to ` ‘((0 1) (3 4) (6 8) (10 10))`.
A for-loop implementation is not so fast enough, ‘cause its cost is O(N).
As far as we know, this is a sorted and non-duplicated number list.
A binary-search algorithm costing O(log(N)) suits this case the best.
Here is the divide and conquer data flow:
Implement it is really simple:
(merge-range-pairs p1 p2) helps us dealing with (3 4) (5 6):
If start of p2 is next to end of p1, concat them into one pair;
Otherwise, keep them staying 2 pairs.
Here is a possible implementation:
We still leave some trivial procedures to implement, there are many ways to have them.
Here is a praticable entire solution: