# [LeetCode] 163. Missing Ranges 缺失区间

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

Example:

Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99,
Output: ["2", "4->49", "51->74", "76->99"]

class Solution {
public:
vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
vector<string> res;
for (int num : nums) {
if (num > lower) res.push_back(to_string(lower) + (num - 1 > lower ? ("->" + to_string(num - 1)) : ""));
if (num == upper) return res;
lower = num + 1;
}
if (lower <= upper) res.push_back(to_string(lower) + (upper > lower ? ("->" + to_string(upper)) : ""));
return res;
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/163

Summary Ranges

https://leetcode.com/problems/missing-ranges/

https://leetcode.com/problems/missing-ranges/discuss/50468/Accepted-Java-solution-8-lines-and-0ms

 微信打赏 Venmo 打赏
posted @ 2016-02-08 07:21  Grandyang  阅读(15037)  评论(3编辑  收藏  举报