[LeetCode] Summary Ranges

This problem is similar to Missing Ranges and easier than that one.

The idea is to use two pointers to find the beginning and end of a range and then push it into the result.

The code is as follows, which should be self-explanatory.

 1 class Solution {
 2 public:
 3     vector<string> summaryRanges(vector<int>& nums) {
 4         vector<string> ranges;
 5         int left, right, n = nums.size();
 6         for (left = 0; left < n; left = right + 1) {
 7             right = left;
 8             while (right + 1 < n && nums[right] + 1 == nums[right + 1])
 9                 right++;
10             ranges.push_back(getRanges(nums[left], nums[right]));
11         }
12         return ranges;
13     }
14 private:
15     string getRanges(int low, int up) {
16         return (low == up) ? to_string(low) : to_string(low) + "->" + to_string(up);
17     }
18 };

 

posted @ 2015-06-26 14:29  jianchao-li  阅读(276)  评论(0编辑  收藏  举报