228 Summary Range
//额外声明:我发现不必把做的每一道题都在博客里更新,今后将更新我认为比较有意思的题目
Descroption:
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"].
给定一个排过序的无重复整形数组,返回其连续分组。这个题目标注难度为easy,但我着实耗费了一些时间,最终的代码也不够清晰,我除将把自己的代码列出来外,会再展示一个讨论区里面我认为逻辑清楚的代码作为比较,以供自己不时参考。
下面是我自己的代码:
1 class Solution { 2 public: 3 struct group{ 4 group(): begin(0), end(0), tag(false) {} 5 void reset() { 6 begin = 0; 7 end = 0; 8 tag = false; 9 } 10 int begin; 11 int end; 12 bool tag; 13 }; 14 vector<string> summaryRanges(vector<int>& nums) { 15 vector<group> vec; 16 vector<string> s; 17 if(nums.empty()) return s; 18 int cur = nums[0] - 1; 19 group p; 20 p.begin = nums[0]; 21 for(auto it: nums) { 22 if(it == cur + 1) { 23 if(it != p.begin) { 24 p.end = it; 25 p.tag = true; 26 } 27 } else { 28 vec.push_back(p); 29 p.reset(); 30 p.begin = it; 31 } 32 cur = it; 33 } 34 vec.push_back(p); 35 for(int i = 0; i < vec.size(); i++) { 36 char t[30]; 37 sprintf(t, "%d", vec[i].begin); 38 string ss(t, t + strlen(t)); 39 if(vec[i].tag) { 40 ss += "->"; 41 char u[30]; 42 sprintf(u, "%d", vec[i].end); 43 ss += string(u, u+ strlen(u)); 44 } 45 s.push_back(ss); 46 } 47 return s; 48 } 49 };
更好的代码:
1 class Solution { 2 public: 3 string buildString(int rangeStart, int rangeEnd) { 4 string s; 5 6 char buffer [33]; 7 8 sprintf(buffer,"%d",rangeStart); 9 s.append(buffer); 10 11 if (rangeStart != rangeEnd) 12 { 13 s.append("->"); 14 15 sprintf(buffer,"%d",rangeEnd); 16 s.append(buffer); 17 } 18 19 return s; 20 } 21 22 vector<string> summaryRanges(vector<int>& nums) { 23 vector<string> o; 24 int rangeStart = 0; 25 int rangeEnd = 0; 26 27 if (nums.size() != 0) 28 { 29 for(int i = 0; i < nums.size(); i++) 30 { 31 if(i == nums.size()-1) 32 { 33 rangeEnd = i; 34 string s = buildString(nums[rangeStart],nums[rangeEnd]); 35 o.push_back(s); 36 } 37 else 38 if((nums[i+1] == nums[i]+1)) 39 { 40 rangeEnd++; 41 } 42 else 43 { 44 string s = buildString(nums[rangeStart],nums[rangeEnd]); 45 o.push_back(s); 46 rangeStart = i+1; 47 rangeEnd = i+1; 48 } 49 } 50 } 51 52 return o; 53 } 54 };