228. Summary Ranges - CPP - Solution


  • 0
    Y
    // 228. Summary Ranges
    // https://leetcode.com/problems/summary-ranges/
    #include <iostream>
    #include <vector> // required for vector container
    #include <string> // required for string container and to_string() function
    using namespace std;
    class Solution {
    public:
    	vector<string> summaryRanges(const vector<int>& nums) {
    		vector<string> result;
    		vector<int> range;
    		string s = "";
    		for (size_t i = 0; i < nums.size(); ++i) {
    			if (range.empty()) {
    				range.push_back(nums[i]);
    				if (i + 1 == nums.size()) {
    					s = to_string(nums[i]);
    					result.push_back(s);
    					range.clear();
    				}
    			}
    			else if (!range.empty()) {
    				if (range.back() + 1 == nums[i]) {
    					range.push_back(nums[i]);
    					if (i + 1 == nums.size()) {
    						s = to_string(range.front()) + "->" + to_string(range.back());
    						result.push_back(s);
    						range.clear();
    					}
    				}
    				else if (range.back() + 1 != nums[i]) {
    					if (range.size() == 1) {
    						s = to_string(range.front());
    						result.push_back(s);
    						range.clear();
    						range.push_back(nums[i]);
    						if (i + 1 == nums.size()) {
    							s = to_string(nums[i]);
    							result.push_back(s);
    							range.clear();
    						}
    					}
    					else if (range.size() >= 2) {
    						s = to_string(range.front()) + "->" + to_string(range.back());
    						result.push_back(s);
    						range.clear();
    						range.push_back(nums[i]);
    						if (i + 1 == nums.size()) {
    							s = to_string(nums[i]);
    							result.push_back(s);
    							range.clear();
    						}
    					}
    				}
    			}
    		}
    		return result;
    	}
    };
    int main(int argc, const char** argv) {
    	Solution solution;
    	vector<int> nums = { 0,1,2,4,5,7 };
    	for (const auto& i : solution.summaryRanges(nums)) {
    		cout << i << '\n';
    	}
    	getchar();
    	return 0;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.