題目連結(https://leetcode.com/problems/summary-ranges/description)
You are given a sorted unique integer array nums
.
A range [a,b]
is the set of all integers from a
to b
(inclusive).
Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums
is covered by exactly one of the ranges, and there is no integer x
such that x
is in one of the ranges but not in nums
.
Each range [a,b]
in the list should be output as:
"a->b"
if a != b
"a"
if a == b
限制條件
0 <= nums.length <= 20
2^31 <= nums[i] <= 2^31 - 1
nums
are unique.nums
is sorted in ascending order.寫這題需要知道字串的基本用法
想清楚兩種構成區間的情況與邊界條件
nums
,陣列中的元素都是唯一的。nums
排序是升序,且數都是唯一的,介於整數範圍。區間覆蓋範圍不能超過陣列中的數,比如說不能直接用0→4,因為沒有3。
此外,也可能出現單個數字的情況,比如說陣列最後一個數字 7 前後都沒有連續的數字。
Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: The ranges are:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"
a
。a->b
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> result;
// 處理空陣列
if(nums.empty()) return result;
int begin = 0;
for(int i = 0; i < nums.size(); i++){
// 檢查是否到達array末位,或者當前數字與下一個數字不連續(不在同區間)
if(i == nums.size() - 1 || nums[i+1] != nums[i] + 1){
if(begin == i){ //只有一個數字直接加入result
result.push_back(to_string(nums[begin]));
}
else{
result.push_back(to_string(nums[begin]) + "->" + to_string(nums[i]));
}
// 更新下一個區間的開始位置
begin = i + 1;
}
//如果連續的話不會進去if,i 直接加 1,begin 並不會加 1
}
return result;
}
};
nums | Output |
---|---|
[0,1,2,4,5,7] |
["0->2", "4->5", "7"] |
[0,2,3,4,6,8,9] |
["0", "2->4", "6", "8->9"] |
[] |
[] |
[1] |
["1"] |
1. 溢位問題:
nums[i+1] - nums[i] != 1
會有問題,因為在處理兩個數字的差時,可能會出現溢位的情況(例如 nums[i] = INT_MIN
-2147483648,nums[i+1] = INT_MAX
,這樣會造成溢位)。nums[i+1] != nums[i] + 1
,這樣可以避免溢位的問題,保證數字不會超過整數範圍。2. 條件檢查順序:
條件的檢查順序很重要,如果將以下檢查的順序調換:
if (i == nums.size() - 1 || nums[i+1] != nums[i] + 1)
會在最後一個數字時出現 runtime error
。因為在最後一個數字時,i+1
的位置超出了陣列範圍,會觸發訪問越界錯誤。
3. 字串相關語法
to_string()
:將整數轉為字串。push_back()
:將元素添加到 vector
的末尾。ps. 部分內容經 AI 協助整理