标签:
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)初始化两个游标ind1=0,ind2=1,一个左边界left=ind1;(2)若nums[ind2]-nums[ind1]==1则ind1++、ind2++,否则可以得到一个范围[nums[left], nums[ind2-1]],将其存入结果中,同时更新游标ind1=ind2,且ind2++,更新左边界left=ind1;(3)若ind2<nums.size(),则跳转到(2),否则处理最后剩下的一个范围。
class Solution2 { public: vector<string> summaryRanges(vector<int>& nums) { int n = nums.size(); if (n == 0) return vector<string>(); if (n == 1) return vector<string>(1, intToString(nums[0])); int ind1 = 0; int ind2 = 1; int left = ind1; vector<string> res; while (ind1 < n && ind2 < n) { if (nums[ind2] == nums[ind1] + 1) { ind2++; ind1++; } else { string rs = ""; rs += intToString(nums[left]); if (ind2 - 1 != left) rs += "->" + intToString(nums[ind2 - 1]); left = ind1 = ind2++; res.push_back(rs); } } string rs = ""; rs += intToString(nums[left]); if (--ind2 != left) rs += "->" + intToString(nums[ind2]); res.push_back(rs); return res; } private: string intToString(const int& i) { stringstream ss; ss << i; string s = ss.str(); return s; } };
注意:(1)考虑nums.size()为0或者1的情况;(2)整数转换为string的处理,考虑负数、最小的整数和最大的整数这些极端情况。可以使用to_string()。
[LeetCode]8. Summary Ranges统计范围
标签:
原文地址:http://www.cnblogs.com/aprilcheny/p/4854198.html