leetcode-228. Summary Ranges

来源:互联网 发布:财政部ppp中心数据 编辑:程序博客网 时间:2024/05/17 08:25

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”].

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

class Solution {public:    vector<string> summaryRanges(vector<int>& nums) {        int length = nums.size();        vector<string> res;        if(length == 0)        {            return res;        }        string temp;        for(int i=0;i<length;)        {            int start = i;            int end = i;            while(end + 1 < length && nums[end] == nums[end+1]-1)            {                end++;            }            if(nums[end] > nums[start])            {                temp = to_string(nums[start]) + "->" + to_string(nums[end]);                res.push_back(temp);            }            else            {                temp = to_string(nums[start]);                res.push_back(temp);            }            i = end+1;        }        return res;    }};
0 0
原创粉丝点击