分享

leetcode试题1

 _小女子_ 2015-06-28

原题:https:///problems/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"].

C++答案:


#include "stdafx.h"
using namespace std;
#include "vector"
#include <iostream> 

class Sloution{
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> result;
string s = "";
int j = 0;
int end_flag = 0;
int beg_flag = 0;
bool f = false;
while (beg_flag<nums.size()){
if (nums.size()>1 && beg_flag+1<nums.size()){
char t[16];
if ((nums.at(beg_flag + 1) - nums.at(beg_flag) == 1)){
sprintf_s(t, "%d->", nums.at(beg_flag));
s = t;
}
else{
sprintf_s(t, "%d", nums.at(beg_flag));
result.push_back(t);
f = true;
beg_flag++;
end_flag++;
continue;
}
}
for (int i = beg_flag; i < nums.size(); i++){
f = false;
if (i + 1 >= nums.size()){
if (!f){
char t2[16];
sprintf_s(t2, "%d", nums.at(beg_flag));
s.append(t2);
result.push_back(s);
s = "";
f = false;
}
beg_flag++;
break;
}
if ((nums.at(i + 1) - nums.at(i) == 1)){
f = false;
end_flag ++;
beg_flag = end_flag ;
}
else{
j++;
//numsArray.resize(j);
if (!f){
char t1[16];
sprintf_s(t1, "%d", nums.at(end_flag));
s.append(t1);
result.push_back(s);
s = "";
f = false;
}
//numsArray.push_back({ nums.at(beg_flag), nums.at(end_flag) });
beg_flag = end_flag+1;
end_flag = beg_flag;
break;
}
}
}
return result;
}

};
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> nums = { 1 ,3,4,5,7};
vector<int> nums1 = { 0,1};
vector<int> nums2 = { 1 };
Sloution s;
vector<string> result=s.summaryRanges(nums);
for (int i = 0; i < result.size(); i++){
printf("%s", result.at(i).c_str());
//cout << result.at(i);
}
int i = 0;
cin >> i;
return 0;
}


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多