zoukankan      html  css  js  c++  java
  • Leetcode 228. Summary Ranges

    228. Summary Ranges

    • Total Accepted: 51769
    • Total Submissions: 203058
    • Difficulty: Medium

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

    思路:见代码。

    注意c++中数字转换为string可以用to_string()函数。

    实现string和int的相互转换可以用stringstream。

    代码:

    用to_string()函数:

     1 class Solution {
     2 public:
     3     vector<string> summaryRanges(vector<int>& nums) {
     4         int low=0,high=0,n=nums.size(),i;
     5         vector<string> res;
     6         string lows,highs;
     7         while(high<n){
     8             lows=to_string(nums[low]);
     9             i=0;
    10             while(high<n&&nums[low]+i==nums[high]){
    11                 i++;
    12                 high++;
    13             }
    14             if(i>1){
    15                 highs=to_string(nums[high-1]);
    16                 lows=lows+"->"+highs;
    17             }
    18             res.push_back(lows);
    19             low=high;
    20         }
    21         return res;
    22     }
    23 };

    用stringstream:如果想通过使用同一stringstream对象实现多种类型的转换,请注意在每一次转换之后都必须调用clear()成员函数

     1 class Solution {
     2 public:
     3     vector<string> summaryRanges(vector<int>& nums) {
     4         int low=0,high=0,n=nums.size(),i;
     5         vector<string> res;
     6         stringstream ss;
     7         string lows,highs;
     8         while(high<n){
     9             ss<<nums[low];
    10             ss>>lows;
    11             ss.clear();
    12             i=0;
    13             while(high<n&&nums[low]+i==nums[high]){
    14                 i++;
    15                 high++;
    16             }
    17             if(i>1){
    18                 ss<<nums[high-1];
    19                 ss>>highs;
    20                 ss.clear();
    21                 lows=lows+"->"+highs;
    22             }
    23             res.push_back(lows);
    24             low=high;
    25         }
    26         return res;
    27     }
    28 };
  • 相关阅读:
    python使用win32api截图并回收资源
    tesseract-ocr的安装及使用
    python识别图片文字
    Python中CreateCompatibleDC和CreateBitmap造成的内存泄漏
    Python调用windows API实现屏幕截图
    turtle库常用函数
    Python3.6安装turtle模块
    Python中的截屏模块 pyscreenshot
    Python实现屏幕截图的两种方式
    观察者模式(Observer Pattern)
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5717079.html
Copyright © 2011-2022 走看看