【LeetCode 228_陣列】Summary Ranges

QingLiXueShi發表於2015-07-06

 1 vector<string> summaryRanges(vector<int>& nums)
 2 {
 3     int nums_len = nums.size();
 4     vector<string> res;
 5     if (nums_len == 0)
 6         return res;
 7     
 8     for (int i = 0; i < nums_len;) {
 9         int start = i, end = i;
10         while (end + 1 < nums_len && nums[end + 1] == nums[end] + 1) end++;
11         if (end > start)
12             res.push_back(to_string(nums[start]) + "->" + to_string(nums[end]));
13         else
14             res.push_back(to_string(nums[start]));
15         i = end + 1;
16     }
17     return res;
18 }

 

相關文章