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

    Example 2:

    Input: [0,2,3,4,6,8,9]
    Output: ["0","2->4","6","8->9"]
    

    题目标签:Array

      题目给了我们一个nums array, 让我们找出它的区间总结。

      这题可以用two pointers 来做, 设一个left 和 right 起初都等于0。遍历nums array,如果遇到了 当前数字 等于 前一个数字+1, 那么就把right = i,扩大这个sliding window 的范围;如果遇到的 当前数字 不等于 前一个数字+1,意味着此时需要把前面的区间left 到 right加入list,因为这里已经断点了。而且还需要更新left 和 right 都等于 目前的 i, 让sliding window 重新开始。

      还需要注意的是,遍历完nums 之后,还需要把最后的区间 加入 list。

    Java Solution:

    Runtime beats 51.99% 

    完成日期:09/06/2017

    关键词:Array, Two Pointers

    关键点:利用left 和 right 来控制sliding window 的大小(区间)

     1 class Solution 
     2 {
     3     public List<String> summaryRanges(int[] nums) 
     4     {
     5         List<String> res = new ArrayList<>();
     6         
     7         if(nums == null || nums.length == 0)
     8             return res;
     9         
    10         int left = 0, right = 0;
    11         
    12         for(int i=1; i<nums.length; i++)
    13         {
    14             // if current number is not equal to previous number + 1, add the range into list
    15             if(nums[i] != nums[i-1] + 1)
    16             {
    17                 // if just one number
    18                 if(left == right)
    19                     res.add("" + nums[left]);
    20                 else// if more than one number
    21                     res.add("" + nums[left] + "->" + nums[right]);
    22                 
    23                 // if find the gap, update the left and right
    24                 left = i;
    25                 right = i;
    26             }
    27             else if(nums[i] == nums[i-1] + 1) // if find the correct number, increase right
    28                 right = i;
    29             
    30         }
    31         
    32         // add the last range
    33         if(left == right)
    34             res.add("" + nums[left]);
    35         else // if more than one number
    36             res.add("" + nums[left] + "->" + nums[right]);
    37         
    38         return res;
    39     }
    40 }

    参考资料:N/A

    LeetCode 算法题目列表 - LeetCode Algorithms Questions List

  • 相关阅读:
    Spark_3:Spark集群搭建
    Spark_2:Spark 快速入门教程
    Spark快速大数据分析_11:第十一章
    Spark快速大数据分析_10:第十章
    Spark快速大数据分析_9:第九章
    Spark快速大数据分析_8:第八章
    Spark快速大数据分析_7:第七章
    Spark快速大数据分析_6:第六章
    Spark快速大数据分析_5:第五章
    java 内部类详解
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7488181.html
Copyright © 2011-2022 走看看