您的位置:首页 > 其它

[LeetCode] Summary Ranges

2016-04-07 13:11 316 查看
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"].


Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

解题思路:

这道题题意是,将相邻的一组数据用区间表示。尽管mark为easy,可是麻雀虽小,却五脏俱全,有非常多陷阱的问题。

1、最開始想的是例如以下代码。但有几个问题须要注意一下。一个就是可能溢出问题,这体如今两个方面。一个是自行编写的数字转字符串的代码中,还有一个是在推断两个数是否相邻。

由于对c++不够了解,因此居然不知道怎样将数字转化成字符串,于是动手写了一个。

囧。

这个版本号的代码就像懒婆娘的裹脚布一样。

class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
int len = nums.size();
vector<string> result;
if(len == 0){
return result;
}
int left = nums[0];
nums.push_back(nums[len-1]);
len++;
for(int i=1; i<len; i++){
if(nums[i] == nums[i-1] || ((long long)nums[i] - (long long)nums[i-1] > 1)){
if(left == nums[i-1]){
result.push_back(intToString(left));
}else{
result.push_back(intToString(left) + "->" + intToString(nums[i-1]));
}
left = nums[i];
}
}
return result;
}

string intToString(int n){
if(n==0){
return "0";
}
long long lN = n;
string s = "";
if(lN<0){
s = "-";
lN = -lN;
}
stack<char> stacks;
while(lN!=0){
stacks.push(lN%10 + '0');
lN = lN/10;
}
while(!stacks.empty()){
s += stacks.top();
stacks.pop();
}
return s;
}
};
2、事实上c++中能够直接将数字转化成字符串的。

在<string>头文件里,有这么一个方法to_string。另外。推断是否相邻应该用不等号。因此,精简后的代码例如以下。

以上两个版本号都是先在后面加入一个哨兵数据。

class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
int len = nums.size();
vector<string> result;
if(len == 0){
return result;
}
int left = nums[0];
nums.push_back(nums[len-1]);
len++;
for(int i=1; i<len; i++){
if(nums[i] == nums[i-1] || nums[i] - nums[i-1] != 1){
if(left == nums[i-1]){
result.push_back(to_string(left));
}else{
result.push_back(to_string(left) + "->" + to_string(nums[i-1]));
}
left = nums[i];
}
}
return result;
}
};
3、在网上找到第二种解决方式。很优雅,其答题思路就是找到每一个区间的左右两个端点,且无需哨兵。

class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
int len = nums.size();
int i=0;
vector<string> result;
while(i<len){
int j=1;
while(i+j<len && nums[i+j] - nums[i] == j) j++;
result.push_back(j==1 ? to_string(nums[i]) : to_string(nums[i]) + "->" + to_string(nums[i + j - 1]));
i += j;
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: