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"].
就是概括区间的方式把一个数组表示下来,例如123用1->3代替,自己写的很乱 ,维护两个指针就可以了:
1 class Solution { 2 public: 3 vector<string> summaryRanges(vector<int>& nums) { 4 int start = 0; 5 stringstream str; 6 vector<string> ret; 7 int sz = nums.size(); 8 if(sz == 0) return ret; 9 if(sz == 1){ 10 str << nums[0]; 11 ret.push_back(str.str()); 12 return ret; 13 } 14 //str << nums[0]; 15 start = nums[0]; 16 for(int i = 1; i < sz; ++i){ 17 if(nums[i] == nums[i-1] + 1) continue; 18 if(start != nums[i - 1]) //防止单个数字是一个区间的情况 19 str << start << "->" << nums[i - 1]; 20 else 21 str << start; 22 ret.push_back(str.str()); 23 start = nums[i]; 24 str.str(""); 25 } 26 if(nums[sz - 1] == nums[sz - 2] + 1){ 27 str << start << "->" << nums[sz - 1]; 28 ret.push_back(str.str()); 29 }else{ 30 str << nums[sz - 1]; 31 ret.push_back(str.str()); 32 } 33 return ret; 34 } 35 };
时间: 2024-11-01 20:57:23