zoukankan      html  css  js  c++  java
  • 228. [LeetCode] Summary Ranges

    Given a sorted integer array without duplicates, return the summary of its ranges.

    Example 1:

    Input:  [0,1,2,4,5,7]
    Output: ["0->2","4->5","7"]
    Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
    

    Example 2:

    Input:  [0,2,3,4,6,8,9]
    Output: ["0","2->4","6","8->9"]
    Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.





    class Solution {
    public:
           vector<string> summaryRanges(vector<int>& nums) {
        const int size_n = nums.size();
        vector<string> res;
        if ( 0 == size_n) return res;
        for (int i = 0; i < size_n;) {
            int start = i, end = i;
            while (end + 1 < size_n && nums[end+1] == nums[end] + 1) end++;
            if (end > start) res.push_back(to_string(nums[start]) + "->" + to_string(nums[end]));
            else res.push_back(to_string(nums[start]));
            i = end+1;
        }
        return res;
    }
    };
    class Solution {
    public:
        vector<string> summaryRanges(vector<int>& nums) {
            vector<string> result;
            if(!nums.size()) return result;
        int low = nums[0], high = nums[0];
        for(int i = 1; i < nums.size(); i++){
            if (nums[i] == high + 1)
                high++;
            else{
                result.push_back(low == high ? to_string(low) : to_string(low) + "->" + to_string(high));
                low = high = nums[i];
            }
        }
        result.push_back(low == high ? to_string(low) : to_string(low) + "->" + to_string(high));
        return result;
        }
    };
  • 相关阅读:
    Code Review 五问五答
    JavaScript 10分钟入门
    swagger editor使用
    Tyk API网关介绍及安装说明
    Castle 多继承选择
    线程信息的获取和设置
    s3 api接口的调用
    在Hadoop集群上的HBase配置
    OpenStack 单元测试
    在Hadoop集群上的Hive配置
  • 原文地址:https://www.cnblogs.com/250101249-sxy/p/10436497.html
Copyright © 2011-2022 走看看