[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.

The code is as follows, which should be self-explanatory.

复制代码
 1 class Solution {
 2 public:
 3     vector<string> summaryRanges(vector<int>& nums) {
 4         vector<string> ranges;
 5         int left, right, n = nums.size();
 6         for (left = 0; left < n; left = right + 1) {
 7             right = left;
 8             while (right + 1 < n && nums[right] + 1 == nums[right + 1])
 9                 right++;
10             ranges.push_back(getRanges(nums[left], nums[right]));
11         }
12         return ranges;
13     }
14 private:
15     string getRanges(int low, int up) {
16         return (low == up) ? to_string(low) : to_string(low) + "->" + to_string(up);
17     }
18 };
复制代码

 

posted @   jianchao-li  阅读(278)  评论(0编辑  收藏  举报
编辑推荐:
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
阅读排行:
· 从零开始开发一个 MCP Server!
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
点击右上角即可分享
微信分享提示