码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_228题——Summary Ranges

时间:2015-07-16 11:08:11      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

Summary Ranges

 Total Accepted: 9278 Total Submissions: 48419My Submissions

 

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.

 

Hide Tags
 Array
Hide Similar Problems
 (M) Missing Ranges
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

#include<iostream>
#include<string>
#include<vector>
#include<math.h>
using namespace std;


//将整数转化为字符串输出,这里需要考虑整数的大小,
//开始使用int发现在最小的负值时时不行的。
string ToString(long long int n)
{
	string str;
	if(n<0)
		{
			str.push_back(‘-‘);
			n=-n;
	}
	string str1;
	while(1)
	{
		int b=n%10;
		str1.push_back(b+48);
		n=n/10;
		if(n==0)
			break;
	}
	while(!str1.empty())
	{
		str.push_back(str1.back());
		str1.pop_back();
	}
	return str;
}

vector<string> summaryRanges(vector<int>& nums) {
	vector<string> vec;
	string str;
	if(nums.empty())
		return vec;
	int n=nums.size();
	int i=0;
	while(i<n)
	{
		int a1=nums[i];
		if(i==n-1)
		{
			str.clear();
			str=ToString(nums[i]);
			vec.push_back(str);
			break;
		}
		int a2;
		int j=i+1;
		while(j<n)
		{
			if(j>n)
				break;
			if(nums[j]==nums[j-1]+1)
				j++;
			else
				break;
		}
		a2=nums[j-1];
		if(j-1==i)
		{
			str.clear();
			str=ToString(nums[i]);
			vec.push_back(str);
		}
		else
		{
			str.clear();
			int a;
			str=ToString(nums[i]);
			str=str+"->";
			str=str+ToString(nums[j-1]);
			vec.push_back(str);
		}
		i=j;
	}
	return vec;
}
int main()
{
	/*
	int a[10]={-2147483648,-2147483647,2147483647};
	vector<int> vec(a,a+3);
	vector<string> re=summaryRanges(vec);

	int n=re.size();
	for(vector<string>::iterator i=re.begin();i!=re.end();i++)
	{
		cout<<*i<<endl;
	}*/

	string str=ToString(-1);
	cout<<str<<endl;

}

  

leetcode_228题——Summary Ranges

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4650350.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!