leetcode-Summary Ranges-228
输入一个递增数组,没有重复的元素,输出数组的分段
For example, given [0,1,2,4,5,7]
, return ["0->2","4->5","7"]
已经有序了,所以直接遍历
1 class Solution { 2 public: 3 vector<string> summaryRanges(vector<int>& nums) { 4 vector<string> v; 5 int len=nums.size(); 6 if(len==0) return v; 7 int low=nums[0]; 8 if(len==1){ 9 char a[20]; 10 sprintf(a,"%d",low); 11 string s=a; 12 v.push_back(s); 13 return v; 14 } 15 int high; 16 for(int i=1;i<len;i++){ 17 if(nums[i]==nums[i-1]+1) continue; 18 high=nums[i-1]; 19 char a[20]; 20 sprintf(a,"%d",low); 21 string s=a; 22 if(low!=high){ 23 s+="->"; 24 char b[20]; 25 sprintf(b,"%d",high); 26 s+=b; 27 } 28 v.push_back(s); 29 low=nums[i]; 30 } 31 high=nums[len-1]; 32 char a[20]; 33 sprintf(a,"%d",low); 34 string s=a; 35 if(low!=high){ 36 s+="->"; 37 char b[20]; 38 sprintf(b,"%d",high); 39 s+=b; 40 } 41 v.push_back(s); 42 return v; 43 } 44 };