题目:
228. Summary Ranges
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即可,主要是注意最后的数字要特殊考虑一下。
链接:
https://leetcode.com/problems/summary-ranges/
代码:
1 #include <vector> 2 #include <string> 3 #include <sstream> 4 5 using std::vector; 6 using std::string; 7 using std::ostringstream; 8 9 class Solution { 10 private: 11 string num2str(int& num) 12 { 13 ostringstream stream; 14 stream << num; 15 return stream.str(); 16 } 17 18 public: 19 vector<string> summaryRanges(vector<int>& nums) { 20 unsigned int len = nums.size(); 21 unsigned int index,inIndex; 22 unsigned int minIndex = 0; 23 unsigned int maxIndex = 0; 24 25 vector<string> ans; 26 if(len == 0) 27 { 28 return ans; 29 } 30 31 if(len == 1) 32 { 33 ans.push_back(num2str(nums[0])); 34 return ans; 35 } 36 37 for(index = 0; index < len - 1; ++ index) 38 { 39 if(nums[index] + 1 == nums[index + 1]) 40 { 41 maxIndex = index + 1; 42 }else 43 { 44 string tmp = ""; 45 tmp += num2str(nums[minIndex]); 46 if(maxIndex > minIndex) 47 { 48 tmp += "->"; 49 tmp += num2str(nums[maxIndex]); 50 } 51 ans.push_back(tmp); 52 53 minIndex = index + 1; 54 maxIndex = index + 1; 55 } 56 } 57 58 if(nums[len-2] + 1 == nums[len - 1]) 59 { 60 maxIndex = len - 1; 61 }else 62 { 63 minIndex = len - 1; 64 maxIndex = len - 1; 65 } 66 67 string tmp = ""; 68 tmp += num2str(nums[minIndex]); 69 if(maxIndex > minIndex) 70 { 71 tmp += "->"; 72 tmp += num2str(nums[maxIndex]); 73 } 74 ans.push_back(tmp); 75 76 return ans; 77 } 78 };