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 }
  • 相关阅读:
    BZOJ 1101 莫比乌斯函数+分块
    BZOJ 2045 容斥原理
    BZOJ 4636 (动态开节点)线段树
    BZOJ 2005 容斥原理
    BZOJ 2190 欧拉函数
    BZOJ 2818 欧拉函数
    BZOJ 3123 主席树 启发式合并
    812. Largest Triangle Area
    805. Split Array With Same Average
    794. Valid Tic-Tac-Toe State
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9201916.html
Copyright © 2011-2022 走看看