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> rangs; auto beg = nums.begin(), end = nums.end(); vector<int>::iterator temp=beg; if (nums.size() == 0)return rangs; else{ for (; beg != end-1;++beg){ if (*beg+1 != (*(beg + 1))) { if (temp == beg)rangs.push_back(to_string(*temp)); else rangs.push_back(to_string(*temp) + "->" + to_string(*beg)); temp = beg + 1; } } if (temp == end - 1)rangs.push_back(to_string(*temp)); else rangs.push_back(to_string(*temp) + "->" + to_string(*(end - 1))); } return rangs; } };
求解范围时,必须知道下一个元素是否是上一个元素+1,如果是则不插入到rangs中去,如果不是则要插入进去。插入到rangs中要分两种情况,看是一个元素形成的范围,还是多个元素形成的范围