Leetcode专题[数组]-228-汇总区间

力扣链接:https://leetcode-cn.com/probl...
解题思路:

  1. 汇总区间这个题目跟之前一个输出排序区间的题目有点像。首次拿到这个题目,脑海中先想到的就是双指针的做法,先选定算法,再分析细节
  2. 在选择双指针之后,首先要确定遍历对象,那就是整个数组,通过循环来遍历整个数组
  3. 起始时双指针均位于数组的第一个元素,然后快指针开始遍历,直到找到第一个不连续递增的数字,然后再和慢指针的下标做比较,如果此时快慢指针相等,那么说明这个区间中只有一个数字,加入数组即可。如果快指针大于慢指针,那么插入区间
  4. 最后更新指针,快指针加一,慢指针等于快指针,开始下一轮循环直至结束
func Summary(nums []int) []string {
    n := len(nums)
    if n == 0 {
        return []string{}
    }
    low, high := 0, 0
    ans := []string{}
    for high < n {
        for high < n-1 && nums[high]+1 == nums[high+1] {
            high++
        }
        if low == high {
            ans = append(ans, strconv.Itoa(nums[low]))
        } else if low < high {
            ans = append(ans, strconv.Itoa(nums[low])+"->"+strconv.Itoa(nums[high]))
        }
        high++
        low = high
    }
    return ans
}

你可能感兴趣的:(golang)