[leetcode] Summary Ranges

来源:互联网 发布:linux下安装 seafile 编辑:程序博客网 时间:2024/05/24 06:45

题目链接在此

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

题目意思就是把连续的递增1的子序列用字符串的形式表示出来。并不是很难,但是po上来,是为了纪念一下我在解题过程中发现的“新大陆”:

to_string 可以把数字转成字符串,很方便。就不需要自己手写函数或者用itoa了。


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


0 0