zoukankan      html  css  js  c++  java
  • 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"].

    Analyse: 

    Check whether neighbouring numbers are continuous. Push a number into the array first to avoid overflow. 

     1 class Solution {
     2 public:
     3     vector<string> summaryRanges(vector<int>& nums) {
     4         vector<string> result;
     5         if(nums.empty()) return result;
     6         
     7         int n = nums.size();
     8         nums.push_back(nums[n - 1]);
     9         n++;
    10         for(int i = 0; i < n - 1; i++) {
    11             int start = nums[i];
    12             while(i < n - 1 && nums[i] + 1 == nums[i + 1])
    13                 i++;
    14             int end = nums[i];
    15             
    16             if(start == end)
    17                 result.push_back(to_string(start));
    18             else
    19                 result.push_back(to_string(start) + "->" + to_string(end));
    20         }
    21         return result;
    22     }
    23 };
  • 相关阅读:
    Xshell相关优化
    Inotify+rsync远程实时同步
    MySQL主从复制故障解决
    Docker部署centos7容器
    Salt-ssh批量部署minion
    MySQL数据库二
    防火墙2
    MySQl数据库
    防火墙
    http原理2
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5722232.html
Copyright © 2011-2022 走看看