Missing Ranges -- LeetCode

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     string printRange(int lower, int upper) {
 4         string low = std::to_string(lower);
 5         string up = std::to_string(upper);
 6         if (lower == upper) return low;
 7         return low + "->" + up;
 8     }
 9     vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
10         vector<string> res;
11         if (nums.size() == 0) res.push_back(printRange(lower, upper));
12         else if (nums.front() > lower) res.push_back(printRange(lower, nums.front() - 1));
13         for (int i = 1, n = nums.size(); i < n; i++)
14             if (nums[i] > nums[i-1] + 1)
15                 res.push_back(printRange(nums[i-1] + 1, nums[i] - 1));
16         if (nums.size() > 0 && nums.back() < upper)
17             res.push_back(printRange(nums.back() + 1, upper));
18         return res;
19     }
20 };

 

posted @ 2016-08-17 11:10  fenshen371  阅读(123)  评论(0编辑  收藏  举报