48. Range Shorthand
A librarian wants a compact way to write the catalogue numbers of the books on a shelf. You are given nums, a sorted array of distinct integers.
Group the numbers into the fewest blocks of consecutive values (each value is exactly one more than the previous). Write a block of two or more numbers as "a->b", where a is its first number and b its last, and write a block of a single number as just that number in text, such as "7".
Return the blocks as an array of strings, in the same order as they appear in nums. An empty array gives an empty result.
Example 1
- Input:
- nums = [10,11,12,15,17,18]
- Output:
- ["10->12","15","17->18"]
- Explanation:
10, 11, 12 form a block, 15 stands alone, and 17, 18 form a block.
Example 2
- Input:
- nums = [3,9,10]
- Output:
- ["3","9->10"]
- Explanation:
3 is alone and 9, 10 form a block.
Constraints
0 ≤ nums.length ≤ 20
-231 ≤ nums[i] ≤ 231 - 1
nums is strictly increasing
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(1) extra