week7
題目
Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7]
Output: [“0->2”,”4->5”,”7”]
Example 2:
Input: [0,2,3,4,6,8,9]
Output: [“0”,”2->4”,”6”,”8->9”]
原題地址:https://leetcode.com/problems/summary-ranges/description/
解析
給定一個無重複的有序數組,要求輸出其範圍,如果元素與後面元素不連續則單獨輸出,否則輸出a->b,其中a表示連續元素的下界,b表示連續元素的上界。
大致思路爲用兩個數標定,begin標定當前比對的已有連續元素的起始位置,present標定當前正在檢測的連續元素的位置,即當前找到的連續元素的最後一個,如果發現後一位連續則將present加1,繼續檢測下一位,否則輸出begin->present,重置begin和present。
代碼
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> result;
int begin = 0, present = 0;
while (present < nums.size()) {
/*檢測到達數組的最後一位,無需檢測下一位*/
if (present == nums.size() - 1) {
if (begin == present) {
result.push_back(changeToString(nums[present]));
}
else {
result.push_back(changeToString(nums[begin]) + "->" + changeToString(nums[present]));
}
break;
}
/*下一位與當前位連續*/
else if (nums[present + 1] == nums[present] + 1) {
++present;
}
/*下一位與當前位不同,且只記錄到一位,則直接輸出該位*/
else if (begin == present) {
result.push_back(changeToString(nums[present]));
++begin;
present = begin;
}
/*下一位與當前位不同,且有多位,輸出起始位->當前位*/
else {
result.push_back(changeToString(nums[begin]) + "->" + changeToString(nums[present]));
begin = (++present);
}
}
return result;
}
/*將int輸入表示爲string輸出*/
string changeToString(int num) {
/*int表示範圍爲-21474836478到2147483647
*-2147483648用int無法表示爲整數2147483648
*因此單獨處理
*/
if (num + 2147483648 == 0) { return "-2147483648"; }
int n = abs(num);
vector<char> inverse;
string result = "";
if (num < 0) {
result += '-';
}
while (n / 10 != 0) {
char tmp = (n % 10) + '0';
inverse.push_back(tmp);
n /= 10;
}
char tmp = (n % 10) + '0';
inverse.push_back(tmp);
for (int i = inverse.size() - 1; i >= 0; --i) {
result += inverse[i];
}
return result;
}
};