Summary Ranges

2017/11/30 posted in  leetcode

Given a sorted integer array without duplicates, return the summary of its ranges.求数组中,连续数字的区间。

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        
        vector<string> result;
        if(nums.size()==0) return result;
        
        int end = nums[0]+1;
        int total = 0;
        if (nums.size()==1) {
            result.push_back(to_string(nums[0]));
            return result;
        }
        nums.push_back(INT_MAX); //充当哨兵
        for (int i=1; i<nums.size(); i++) {
            if (nums[i]==end) {
                end++;
                total++;
                continue;
            }else{
                end = nums[i]+1;
                if (total==0) {
                    result.push_back(to_string(nums[i-1]));
                }else{
                    string tmp = to_string(nums[i-1-total])+"->"+to_string(nums[i-1]);
                    result.push_back(tmp);
                }
                total = 0;
            }
        }
        return result;
    }
};