• 【LeetCode】228


    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"].

    My Solution:

    vector<string> summaryRanges(vector<int>& nums)
        {
            vector<string> ret;
            if(nums.empty())return ret;
            int low=nums[0];
            bool flag=false;
            for(int i=1;i<nums.size();i++){
                while(i<nums.size() && nums[i]==nums[i-1]+1)i++;
                int high=nums[i-1];
                if(low!=high)
             ret.push_back(to_string(low)
    +"->"+to_string(high)); else ret.push_back(to_string(low)); if(i==nums.size()){ flag=true; break; } low=nums[i]; } if(flag==false)ret.push_back(to_string(low)); return ret; }

    Better Solution:

     1 class Solution {
     2 public:
     3     vector<string> summaryRanges(vector<int>& nums) {    
     4         vector<string> vec;
     5         if(nums.empty())
     6             return vec;
     7     
     8         int low=nums[0],high=nums[0];
     9         for(int i = 1; i < nums.size(); i ++)
    10         {
    11             if(nums[i]-nums[i-1] == 1)high=nums[i];
    12             else
    13             {
    14                 string range;
    15                 if(low != high)
    16                     range = to_string(low) + "->" + to_string(high);
    17                 else
    18                     range = to_string(low);
    19                 vec.push_back(range);
    20                 low = nums[i];
    21                 high = nums[i];
    22             }
    23         }
    24         string range;
    25         if(low != high)
    26             range = to_string(low) + "->" + to_string(high);
    27         else
    28             range = to_string(low);
    29         vec.push_back(range);
    30         return vec;
    31     }
    32 };
  • 相关阅读:
    THINKPHP3.2视频教程
    PHPCMS 学习
    PHPCMS 后台学习
    phpcms 模板学习
    二叉树的创建与遍历(链式存储)
    MySQL基础~~增、删、改、简单查
    队列的基本操作(链队列)
    MySQL基础~~表结构操作
    行编辑程序
    循环链表的基本操作
  • 原文地址:https://www.cnblogs.com/irun/p/4687845.html
Copyright © 2020-2023  润新知