标签:integer color res solution int 成员 string类 turn 情况
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"].
这个题目不难,首先对原序列进行排序,然后要注意对特殊情况的处理。同时,要掌握string类的几个重要成员函数:
class Solution { public: vector<string> summaryRanges(vector<int>& nums) { int n = nums.size(); if (n == 0) return vector<string>(); vector<string> res; sort(nums.begin(), nums.end()); for (int i = 0, j = 0; i <= j && j <= n-1; ) { while (j <= n-2 && nums[j+1] == nums[j] + 1) { ++j; } string tmp; if (j > i) { tmp.append(to_string(nums[i])); tmp.append("->"); tmp.append(to_string(nums[j])); ++j; i = j; } else { tmp.append(to_string(nums[i])); ++i; ++j; } res.push_back(tmp); } return res; } };
标签:integer color res solution int 成员 string类 turn 情况
原文地址:http://www.cnblogs.com/naivecoder/p/6965002.html