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

      

    解决方法:

    1.记录每组开头数字为pre,每移动一位j++(用j来记录相对pre的距离)

    2.逐次判断当前数字是否为pre+j

      如果是,则轮询下一个

      否则,则输出字符串pre~i-1

    tip:

    注意最后一组输出,需要在循环外再做一次

    参考代码:

     1 class Solution {
     2 public:
     3     vector<string> summaryRanges(vector<int>& nums) {
     4         vector<string> res;
     5         if(nums.size()<=0) return res;
     6         int i=0, j=1, pre=0;
     7         string tmp;
     8         for(i=1; i<nums.size(); i++){
     9             if(nums[i]==nums[pre]+j){
    10                 j++;
    11             }else{
    12                 if(j>1) tmp=to_string(nums[pre])+"->"+to_string(nums[i-1]);
    13                 else tmp=to_string(nums[pre]);
    14                 res.push_back(tmp);
    15                 pre=i;
    16                 j=1;
    17             }
    18         }
    19         if(j>1) tmp=to_string(nums[pre])+"->"+to_string(nums[i-1]);
    20         else tmp=to_string(nums[pre]);
    21         res.push_back(tmp);
    22         return res;
    23     }
    24 };
  • 相关阅读:
    12 KLT算法
    1- js vue.js
    复用代码
    计算两个日期相隔的天数(jodd)
    [转]ORA-00907: 缺失右括号
    [转]sql server 数据库日期格式化函数
    [Oralce]Oralce格式化日期
    myeclipse内存配置
    cookie 编码问题
    [转]Oracle 操作字符串的函数
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/12497555.html
Copyright © 2011-2022 走看看