[LeetCode] Missing Ranges

本文深入探讨了如何通过高效算法确定已排序整数数组中缺失的区间范围,详细介绍了从给定数组和范围边界出发,通过迭代计算并返回缺失区间列表的过程。文章以代码实现为例,展示了如何统一处理不同情况,确保代码简洁且易于理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4601221.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值