Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:

Input:  [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.

Example 2:

Input:  [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

这道题给定我们一个有序数组,让我们总结区间,具体来说就是让我们找出连续的序列,然后首尾两个数字之间用个“->"来连接,那么我只需遍历一遍数组即可,每次检查下一个数是不是递增的,如果是,则继续往下遍历,如果不是了,我们还要判断此时是一个数还是一个序列,一个数直接存入结果,序列的话要存入首尾数字和箭头“->"。我们需要两个变量i和j,其中i是连续序列起始数字的位置,j是连续数列的长度,当j为1时,说明只有一个数字,若大于1,则是一个连续序列,代码如下:

class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
int i = , n = nums.size();
while (i < n) {
int j = ;
while (i + j < n && (long)nums[i + j] - nums[i] == j) ++j;
res.push_back(j <= ? to_string(nums[i]) : to_string(nums[i]) + "->" + to_string(nums[i + j - ]));
i += j;
}
return res;
}
};

类似题目:

Missing Ranges

Data Stream as Disjoint Intervals

参考资料:

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

https://leetcode.com/problems/summary-ranges/discuss/63451/9-lines-c%2B%2B-0ms-solution

https://leetcode.com/problems/summary-ranges/discuss/63219/Accepted-JAVA-solution-easy-to-understand

LeetCode All in One 题目讲解汇总(持续更新中...)

最新文章

  1. poj1611 并查集 (路径不压缩)
  2. C# using的一些事
  3. java 16 - 5 LinkedList模拟栈数据结构的集合
  4. oracle 共享池( shared pool )
  5. 【学习笔记】【C语言】算术运算
  6. UVA 350 Pseudo-Random Numbers 伪随机数(简单)
  7. leetcode@ [208] Implement Trie (Prefix Tree)
  8. 我的第一份vim程序
  9. Axiom3D学习日记 3.Cameras, Lights, and Shadows
  10. lua学习:使用Lua处理游戏数据
  11. 创建 OVS vlan100 netwrok - 每天5分钟玩转 OpenStack(137)
  12. mac上虚拟机安装旧版本的macosx 10.8
  13. MYSQL数据库学习五 表的操作和约束
  14. contos最小包安装完后一些准备
  15. git教程:远程仓库
  16. ES6躬行记(2)——扩展运算符和剩余参数
  17. Tracing Memory access of an oracle process : Intel PinTools
  18. Docker启动出现&quot;No space left on device&quot; 或者 docker日志太多导致磁盘占满问题
  19. 码云,git使用 教程-便签
  20. RabbitMQ消息可靠性

热门文章

  1. ASP.NET Core 中文文档 第三章 原理(12)托管
  2. 在web浏览器上显示室内温度(nodeJs+arduino+socket.io)
  3. NopCommerce 在Category 显示Vendor List列表
  4. ToolsCodeTemplate使用
  5. C#开发微信门户及应用(4)--关注用户列表及详细信息管理
  6. EXCEL中多级分类汇总空白字段填充
  7. Python 生成器与迭代器 yield 案例分析
  8. 面向云的.net core开发框架
  9. wamp集成环境开启rewrite伪静态支持
  10. RESTful Api 身份认证安全性设计