Leetcode - Summary Ranges
https://leetcode.com/problems/summary-ranges/
Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7] Output: ["0->2","4->5","7"] Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
It's very similar to merge intervals. But it uses an array of int, so it can't be modified like merge intervals. Using a start pointer to track the start is a way to solve the problem.
func summaryRanges(nums []int) []string { if len(nums) == 0 { return []string{} } result := []string{} start := 0 for i := 1; i < len(nums); i++ { if nums[i] - nums[i-1] > 1 { if start == i - 1 { result = append(result, fmt.Sprintf("%d", nums[start])) } else { result = append(result, fmt.Sprintf("%d->%d", nums[start], nums[i-1])) } start = i } } if start == len(nums)-1 { result = append(result, fmt.Sprintf("%d", nums[start])) } else { result = append(result, fmt.Sprintf("%d->%d", nums[start], nums[len(nums)-1])) } return result }