题目:
228. Summary Ranges
Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7]
, return ["0->2","4->5","7"].
答案:
就是找连续的序列。
直接判断相邻数据大小是否相差为1即可,主要是注意最后的数字要特殊考虑一下。
链接:
https://leetcode.com/problems/summary-ranges/
代码:
#include <vector>
#include <string>
#include <sstream> using std::vector;
using std::string;
using std::ostringstream; class Solution {
private:
string num2str(int& num)
{
ostringstream stream;
stream << num;
return stream.str();
} public:
vector<string> summaryRanges(vector<int>& nums) {
unsigned int len = nums.size();
unsigned int index,inIndex;
unsigned int minIndex = ;
unsigned int maxIndex = ; vector<string> ans;
if(len == )
{
return ans;
} if(len == )
{
ans.push_back(num2str(nums[]));
return ans;
} for(index = ; index < len - ; ++ index)
{
if(nums[index] + == nums[index + ])
{
maxIndex = index + ;
}else
{
string tmp = "";
tmp += num2str(nums[minIndex]);
if(maxIndex > minIndex)
{
tmp += "->";
tmp += num2str(nums[maxIndex]);
}
ans.push_back(tmp); minIndex = index + ;
maxIndex = index + ;
}
} if(nums[len-] + == nums[len - ])
{
maxIndex = len - ;
}else
{
minIndex = len - ;
maxIndex = len - ;
} string tmp = "";
tmp += num2str(nums[minIndex]);
if(maxIndex > minIndex)
{
tmp += "->";
tmp += num2str(nums[maxIndex]);
}
ans.push_back(tmp); return ans;
}
};