0%

# summary-ranges-228

Posted on 2016-10-12 Edited on 2020-01-12 In leetcode Views: Views: Disqus:

#### problem

Given a sorted integer array without duplicates, return the summary of its ranges.

For example, given `[0,1,2,4,5,7]`, return `["0->2","4->5","7"]`.

#### 题解

每一个区间的起点`nums[i]`加上`j`是否等于`nums[i+j]`
参考

#### Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    class Solution {
    public:
        vector<string> summaryRanges(vector<int>& nums) {
            int i = 0, j = 1, n;
            vector<string> res;
            n = nums.size();
            while(i < n){
                j = 1;
                while(j < n && nums[i+j] - nums[i] == j) j++;
                res.push_back(j <= 1 ? to_string(nums[i]) : to_string(nums[i]) + "->" + to_string(nums[i + j - 1]));
                i += j;
            }
            return res;
        }
    };

Related Posts

- Path Sum
- 34_Search_for_a_Range
- invert-binary-tree
- minimum-size-subarray-sum-209
- leetcode no.3

请我喝杯咖啡

WeChat Pay

Alipay

- Post author: Nicksxs
- Post link: https://nicksxs.me/2016/10/12/summary-ranges-228/
- Copyright Notice: All articles in this blog are licensed under BY-NC-SA unless stating additionally.