C++實(shí)現(xiàn)LeetCode(163.缺失區(qū)間)
[LeetCode] 163. Missing Ranges 缺失區(qū)間
Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, upper], 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"]
這道題讓我們求缺失區(qū)間,跟之前那道 Summary Ranges 很類似,給了一個(gè)空間的范圍 [lower upper],缺失的區(qū)間的范圍需要在給定的區(qū)間范圍內(nèi)。遍歷 nums 數(shù)組,假如當(dāng)前數(shù)字 num 大于 lower,說明此時(shí)已經(jīng)有缺失區(qū)間,至少缺失一個(gè) lower 數(shù)字,此時(shí)若 num-1 大于 lower,說明缺失的是一個(gè)區(qū)間 [lower, num-1],否則就只加入一個(gè)數(shù)字即可。由于 OJ 之后加入了許多 tricky 的 test cases,使得論壇上很多解法都 fail 了。其實(shí)很多是跪在了整型溢出,當(dāng)數(shù)組中有整型最大值時(shí),此時(shí) lower 更新為 num+1 時(shí)就會(huì)溢出,所以在更新之前要先判斷一下,若 num 已經(jīng)是整型最大值了,直接返回結(jié)果 res 即可;否則才更新 lower 繼續(xù)循環(huán)。for 循環(huán)退出后,此時(shí)可能還存在缺失區(qū)間,就是此時(shí) lower 還小于等于 upper 時(shí),可以會(huì)缺失 lower 這個(gè)數(shù)字,或者 [lower, upper] 區(qū)間,最后補(bǔ)上這個(gè)區(qū)間就可以通過啦,參見代碼如下:
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
類似題目:
參考資料:
https://leetcode.com/problems/missing-ranges/
https://leetcode.com/problems/missing-ranges/discuss/50468/Accepted-Java-solution-8-lines-and-0ms
到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(163.缺失區(qū)間)的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)缺失區(qū)間內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- C++實(shí)現(xiàn)LeetCode(171.求Excel表列序號(hào))
- C++實(shí)現(xiàn)LeetCode(168.求Excel表列名稱)
- C++實(shí)現(xiàn)LeetCode(167.兩數(shù)之和之二 - 輸入數(shù)組有序)
- C++實(shí)現(xiàn)LeetCode(166.分?jǐn)?shù)轉(zhuǎn)循環(huán)小數(shù))
- C++實(shí)現(xiàn)LeetCode165.版本比較)
- C++實(shí)現(xiàn)LeetCode(164.求最大間距)
- C++實(shí)現(xiàn)LeetCode(228.總結(jié)區(qū)間)
- C++實(shí)現(xiàn)LeetCode(169.求大多數(shù))
相關(guān)文章
深入淺析C/C++語言結(jié)構(gòu)體指針的使用注意事項(xiàng)
這篇文章主要介紹了C/C++語言結(jié)構(gòu)體指針的使用,大家都知道指針在32位系統(tǒng)占用4Byte,在64位系統(tǒng)占用8Byte,下面看下c語言代碼例子2021-12-12
c++中的volatile和variant關(guān)鍵字詳解
大家好,本篇文章主要講的是c++中的volatile和variant關(guān)鍵字詳解,感興趣的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下2022-01-01
用C/C++實(shí)現(xiàn)linux下檢測網(wǎng)絡(luò)接口狀態(tài)
這篇文章主要為大家詳細(xì)介紹了用c/c++實(shí)現(xiàn)linux下檢測網(wǎng)絡(luò)接口狀態(tài),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06
基于Qt實(shí)現(xiàn)可拖動(dòng)自定義控件
這篇文章主要為大家詳細(xì)介紹了如何基于Qt實(shí)現(xiàn)可拖動(dòng)自定義控件,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以了解一下2023-04-04
json格式解析和libjson的用法介紹(關(guān)于cjson的使用方法)
下面小編就為大家?guī)硪黄猨son格式解析和libjson的用法介紹(關(guān)于cjson的使用方法)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-12-12

