給定無重複遞增整數數組,將連續區間合併為 "start->end" 格式,單獨數字輸出 "num"。例:[0,1,2,4,5,7] → ["0->2","4->5","7"]。
維護區間起點 start,掃描至連續性斷裂處,輸出區間,更新起點。
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
int n = nums.size();
for (int i = 0; i < n; ) {
int start = nums[i];
int j = i + 1;
while (j < n && nums[j] == nums[j-1] + 1) ++j;
if (j - 1 > i)
res.push_back(to_string(start) + "->" + to_string(nums[j-1]));
else
res.push_back(to_string(start));
i = j;
}
return res;
}
};
to_string 簡化數字轉字符串i = j 直接跳過已處理區間while 擴展連續區間long long 防溢出(題目數據 int 足夠)