228. Summary Ranges
- Total Accepted: 51769
- Total Submissions: 203058
- Difficulty: Medium
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"].
思路:见代码。
注意c++中数字转换为string可以用to_string()函数。
实现string和int的相互转换可以用stringstream。
代码:
用to_string()函数:
1 class Solution { 2 public: 3 vector<string> summaryRanges(vector<int>& nums) { 4 int low=0,high=0,n=nums.size(),i; 5 vector<string> res; 6 string lows,highs; 7 while(high<n){ 8 lows=to_string(nums[low]); 9 i=0; 10 while(high<n&&nums[low]+i==nums[high]){ 11 i++; 12 high++; 13 } 14 if(i>1){ 15 highs=to_string(nums[high-1]); 16 lows=lows+"->"+highs; 17 } 18 res.push_back(lows); 19 low=high; 20 } 21 return res; 22 } 23 };
用stringstream:如果想通过使用同一stringstream对象实现多种类型的转换,请注意在每一次转换之后都必须调用clear()成员函数
1 class Solution { 2 public: 3 vector<string> summaryRanges(vector<int>& nums) { 4 int low=0,high=0,n=nums.size(),i; 5 vector<string> res; 6 stringstream ss; 7 string lows,highs; 8 while(high<n){ 9 ss<<nums[low]; 10 ss>>lows; 11 ss.clear(); 12 i=0; 13 while(high<n&&nums[low]+i==nums[high]){ 14 i++; 15 high++; 16 } 17 if(i>1){ 18 ss<<nums[high-1]; 19 ss>>highs; 20 ss.clear(); 21 lows=lows+"->"+highs; 22 } 23 res.push_back(lows); 24 low=high; 25 } 26 return res; 27 } 28 };