LeetCode Summary Ranges

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

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> ranges;
        int len = nums.size();
        if (len < 1) {
            return ranges;
        }
        int start = 0;
        
        for (int i=1; i<len; i++) {
            if (nums[i] != nums[i-1] + 1) {
                ranges.push_back(getRange(nums[start], nums[i-1]));
                start = i;
            }
        }
        
        ranges.push_back(getRange(nums[start], nums[len-1]));
        return ranges;
    }
    
    string getRange(int start, int end) {
        char buffer[32] = {0};
        if (start == end) {
            sprintf(buffer, "%d", start);
        } else {
            sprintf(buffer, "%d->%d", start, end);
        }
        return buffer;
    }
};

posted @ 2015-06-26 11:11  卖程序的小歪  阅读(114)  评论(0编辑  收藏  举报