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

    题意:

    给定一个数组,统计其中元素的区间分布。

    思路:

    scan给定数组

    若当前数字 = 前一个数字 + 1 ,则表示continuous range

    若当前数字 != 前一个数字 + 1, 则表示不是continuous range, 即需要wrap前面的部分。

    留心当for循环scan给定数组完毕,wrap了前面的部分,还需要把剩下的start 到 a.length-1 的部分加到result里

    代码:

     1 class Solution {
     2     public List<String> summaryRanges(int[] a) {
     3         List<String> result = new ArrayList<>();
     4         
     5         if(a.length==0){return result;}
     6         
     7         int start = a[0];
     8         for(int i = 1; i < a.length; i++){
     9             if(a[i] != a[i-1] +1){ // 数字不相连,则wrap前面的部分
    10                 group (result, start, a[i-1]);
    11                 start = a[i];
    12             }
    13         }
    14         group (result, start, a[a.length-1]);// 不要忘记for循环之后剩下的一组
    15         return result;   
    16     }
    17     
    18     private void group (List<String>list, int start, int end){
    19         if(start == end){
    20             list.add(start+"");
    21         }else{
    22             list.add(start+"->"+end);
    23         }
    24     }
    25 }
  • 相关阅读:
    【产品设计】设计中的文档管理
    【基础知识】极管类器件的选用
    【Altium Designer】DatabaseLib的使用方法
    【电力电子】功率因素无功功率
    【基础知识】电阻标称阻值查询表
    【元器件】电容的使用
    【EMC】浪涌
    【仪表】电力专用术语
    往mysql中插入一条新的数据
    mysql 中导出表源码
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9201916.html
Copyright © 2011-2022 走看看