码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]228.Summary Ranges

时间:2015-08-04 23:09:52      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:leetcode

题目

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

代码

/*---------------------------------------
*   日期:2015-08-04
*   作者:SJF0115
*   题目: 228.Summary Ranges
*   网址:https://leetcode.com/problems/summary-ranges/
*   结果:AC
*   来源:LeetCode
*   博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
#include <string>
using namespace std;

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        int size = nums.size();
        vector<string> result;
        if(size == 0){
            return result;
        }//if
        int start = 0;
        int end = 0;
        for(int i = 1;i <= size;++i){
            if(i != size && nums[i] == nums[i-1]+1){
                ++end;
            }//if
            else{
                if(start == end){
                    result.push_back(to_string(nums[start]));
                }//if
                else{
                    result.push_back(to_string(nums[start])+"->"+to_string(nums[end]));
                }//else
                start = end + 1;
                end = start;
            }//else
        }//for
        return result;
    }
};

int main(){
    Solution s;
    vector<int> vec = {-2,0,1,2,4,5,8,10,14,15,16};
    vector<string> result = s.summaryRanges(vec);
    for(int i = 0;i < result.size();++i){
        cout<<result[i]<<" ";
    }//for
    cout<<endl;
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

[LeetCode]228.Summary Ranges

标签:leetcode

原文地址:http://blog.csdn.net/sunnyyoona/article/details/47282305

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!