• [leetcode]163. Missing Ranges缺失范围


    Given a sorted integer array nums, where the range of elements are in the inclusive range [lowerupper], return its missing ranges.

    Example:

    Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99,
    Output: ["2", "4->49", "51->74", "76->99"]

    题意:

    给定一个区间和一堆数。统计一下在此区间有哪些数没在数组中出现,结果用区间表示。

    思路:

    这题跟[leetcode]228. Summary Ranges区间统计思路一致

    区别是因为规定了  [lowerupper] 要考虑更多的边界

    代码:

     1 class Solution {
     2     public List<String> findMissingRanges(int[] a, int lower, int upper) {
     3         List<String> result = new ArrayList<>();
     4         
     5         if(a.length == 0) { 
     6             group(result, lower, upper );
     7             return result;   
     8         }
     9         
    10         if(a[0] != lower){
    11             group(result, lower, a[0] - 1);
    12         }
    13               
    14         for(int i = 1; i < a.length; i++ ){
    15             if( a[i] != a[i-1] && a[i] != a[i-1] + 1){
    16                 group(result, a[i-1] + 1, a[i] - 1 );
    17             }
    18         }
    19             
    20         if(upper != a[a.length - 1] ){
    21             group(result, a[a.length - 1] + 1 , upper);
    22         }
    23          return result;
    24     }
    25     
    26     private void group(List<String> list, int start, int end){
    27         if(start  == end ){
    28             list.add(start +"");
    29         }else{
    30             list.add(start  + "->" + end );
    31         }
    32     }
    33 }
  • 相关阅读:
    Spring注解@Component、@Repository、@Service、@Controller区别
    多线程基本知识
    分布式与集群的区别
    Top 10 Uses For A Message Queue
    redis 总结
    redis 学习
    线程控制-延时与守护
    kafka 教程(一)-初识kafka
    Kafka 教程(二)-安装与基础操作
    ZooKeeper-安装
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9201918.html
Copyright © 2020-2023  润新知