Leetcode - Meeting Rooms II
Leetcode - Merge Intervals

Leetcode - Summary Ranges

violet posted @ Mar 31, 2020 02:44:26 AM in 算法 with tags Algorithm Golang array , 227 阅读

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
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter