Leetcode - Merge Intervals
Leetcode - Data Stream as Disjoint Intervals

Leetcode - Missing Ranges

violet posted @ Mar 31, 2020 03:29:51 AM in 算法 with tags Algorithm Golang array , 251 阅读

https://leetcode.com/problems/missing-ranges/

Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, upper], return its missing ranges.

Example:

Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99,
Output: ["2", "4->49", "51->74", "76->99"]

 

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