[LeetCode] Missing Ranges

简介: Problem Description: Given a sorted integer array where the range of elements are [lower, upper] inclusive, return its missing ranges.

Problem Description:

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"].


Well, I guess this problem aims at testing your ability to think throughly. The tricky part in this problem is to take all possible cases into consideration and unify them to give a succinct code.

The code is as follows.

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

 

目录
相关文章
LeetCode 228. Summary Ranges
给定一个无重复元素的有序整数数组,返回数组区间范围的汇总。
72 0
LeetCode 228. Summary Ranges
|
索引 Java
LeetCode 228 Summary Ranges(值域)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50611045 翻译 给定一个无重复的已排序整型数组,返回其中范围的集合。
730 0
[LeetCode] Summary Ranges
Given a sorted integer array without duplicates, return the summary of its ranges. For example, given [0,1,2,4,5,7], return ["0-&gt;2","4-&gt;5","7"]. 解题思路 略 实现代码 C++: // Runtim
1088 0
[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.
890 0
|
2月前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
3月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
54 6
|
3月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
108 2