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

leetcode - Missing Ranges

时间:2015-06-04 17:12:21      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:c++   程序员   面试   

题目:

Missing Ranges

Given a sorted integer array where the range of elements are [0, 99]inclusive, return its missing ranges.
For example, given [0, 1, 3, 50, 75], return[“2”, “4->49”, “51->74”, “76->99”]


void generate_string(int l, int r, vector<string> &res)
{
	if (l>r || l < 0 || r>99)
		return;
	if (l == r)
		res.push_back(to_string(l));
	else
	{
		string s1 = to_string(l),s2="->",s3=to_string(r);
		res.push_back(s1+s2+s3);
	}
}

vector<string> MissingRanges(const vector<int> &nums)
{
	vector<string> res;

	if (nums.empty())
	{
		generate_string(0, 99, res);
		return res;
	}

	if (nums.size() == 1)
	{
		generate_string(0, nums[0]-1, res);
		generate_string(nums[0]+1, 99, res);
		return res;					
	}

	generate_string(0, nums[0] - 1, res);
	for (int i = 1; i < nums.size(); ++i)
	{
		generate_string(nums[i-1]+1, nums[i] - 1, res);
	}
	generate_string(nums.back()+1, 99, res);

	return res;

}






leetcode - Missing Ranges

标签:c++   程序员   面试   

原文地址:http://blog.csdn.net/bupt8846/article/details/46363379

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