class Solution {
public:
string num2str(int num) {
string res;
int p = 0;
long n = num;
if (n < 0) {
res.push_back('-');
p = 1;
n *= (-1);
}
if (n == 0) res.push_back('0');
while (n) {
res.insert(p, 1, n%10 + '0');
n /= 10;
}
return res;
}
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
if (nums.empty()) return res;
string cur;
int f = 0;
for (int i = 0; i <= nums.size(); i++) {
if (i == 0) {
cur += num2str(nums[i]);
} else if (i < nums.size() && nums[i] == nums[i - 1] + 1) {
f = 1;
} else {
if (f) {
cur += "->";
cur += num2str(nums[i - 1]);
}
res.push_back(cur);
cur.erase(cur.begin(), cur.end());
cur += num2str(nums[i]);
f = 0;
}
}
return res;
}
};#1:数组元素可能为负,也不一定是数字,需要辅助函数
#2:注意int的边界案例-2,147,483,647,直接乘-1会出界
本文介绍了一种用于处理整数数组并将其转换为简洁区间的算法实现。该算法能够处理包含负数的情况,并通过自定义函数将整数转换为字符串形式。此外,还特别注意了边界条件处理,如最大int值-2,147,483,647的处理。

被折叠的 条评论
为什么被折叠?



