原题:https:///problems/summary-ranges/ Given a sorted integer array without duplicates, return the summary of its ranges. For example, given #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; } |
|
来自: _小女子_ > 《算法leecode》