[LeetCode] Missing Ranges

Missing Ranges 

Given a sorted integer array where the range of elements are [lowerupper] inclusive, return its missing ranges.

For example, given [0, 1, 3, 50, 75]lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"].

 1 class Solution {
 2 public:
 3     vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
 4         vector<string> res;
 5         for (int i = 0; i < nums.size() && nums[i] <= upper; ++i) {
 6             while (i < nums.size() && nums[i] == lower) {
 7                 ++i;
 8                 ++lower;
 9             }
10             if (i >= nums.size()) break;
11             if (nums[i] == lower + 1) {
12                 res.push_back(to_string(lower));
13             } else {
14                 res.push_back(to_string(lower) + "->" + to_string(nums[i]-1));
15             }
16             lower = nums[i] + 1;
17         }
18         if (lower == upper) {
19             res.push_back(to_string(lower));
20         } else if (lower < upper) {
21             res.push_back(to_string(lower) + "->" + to_string(upper));
22         }
23         return res;
24     }
25 };

 

posted @ 2015-09-07 13:07  Eason Liu  阅读(199)  评论(0编辑  收藏  举报