228. Summary Ranges

来源:互联网 发布:高清网络电视直播 编辑:程序博客网 时间:2024/05/21 15:04

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

Solution:

class Solution {public:    vector<string> summaryRanges(vector<int>& nums) {        vector<string> tmp;        int i = 0;        int pre = 0;        if(nums.empty()) return tmp;        pre = nums[0];        for(;i<nums.size();i++){            if(i+1==nums.size()){                if(pre==nums[i]) {tmp.push_back(to_string(pre));}                else {                    tmp.push_back(to_string(pre)+"->"+to_string(nums[i]));                }                                return tmp;            }            else{                if(nums[i+1]==nums[i]+1) {}                else {                    if(pre==nums[i]) {tmp.push_back(to_string(pre));}                    else{                        tmp.push_back(to_string(pre)+"->"+to_string(nums[i]));                    }                    pre = nums[i+1];                }            }        }            }};
心得:主要考虑corner,程序写的比较繁琐,但逻辑比较清楚

运行速度:快

0 0
原创粉丝点击