Summary Ranges(leetcode 228)

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> a;
        if (nums.size() == 0) {
            return a;
        }
        int begin = nums[0];
        char buff[100];
        for (int i = 1; i <= nums.size(); ++i) {
            if (i < nums.size() && nums[i] - nums[i - 1] == 1) {
                continue;
            } else {
                if (nums[i - 1] == begin) {
                    snprintf(buff, 100, "%d", begin);
                    a.push_back(string(buff));
                } else {
                    snprintf(buff, 100, "%d->%d", begin, nums[i - 1]);
                    a.push_back(string(buff));
                }
                begin = nums[i];
            }

        }
        return a;
    }
};

你可能感兴趣的:(Summary Ranges(leetcode 228))