zoukankan      html  css  js  c++  java
  • LeetCode 632. Smallest Range Covering Elements from K Lists

    原题链接在这里:https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/

    题目:

    You have k lists of sorted integers in ascending order. Find the smallest range that includes at least one number from each of the k lists.

    We define the range [a,b] is smaller than range [c,d] if b-a < d-c or a < c if b-a == d-c.

    Example 1:

    Input: [[4,10,15,24,26], [0,9,12,20], [5,18,22,30]]
    Output: [20,24]
    Explanation: 
    List 1: [4, 10, 15, 24,26], 24 is in range [20,24].
    List 2: [0, 9, 12, 20], 20 is in range [20,24].
    List 3: [5, 18, 22, 30], 22 is in range [20,24].

    Note:

    1. The given list may contain duplicates, so ascending order means >= here.
    2. 1 <= k <= 3500
    3. -105 <= value of elements <= 105.

    题解:

    Consider this question this way, if there are 2 rows, how to do it. We need 2 pointers and move the smaller pointer every time to update smallest range.

    Now we have > 2 rows, we need a PriorityQueue to get the smallest value.

    And we also need to know which row and index of that row, thus we use an array to track all of this.

    Time Complexity: O(n * logk). k = nums.size(). n is length of longest list.

    Space: O(k).

    AC Java: 

     1 class Solution {
     2     public int[] smallestRange(List<List<Integer>> nums) {
     3         if(nums == null || nums.size() == 0){
     4             return new int[0];
     5         }
     6         
     7         int [] res = new int[2];
     8         PriorityQueue<int []> minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
     9         int max = Integer.MIN_VALUE;
    10         int minLen = Integer.MAX_VALUE;
    11         int n = nums.size();
    12         for(int i = 0; i < n; i++){
    13             int num = nums.get(i).get(0);
    14             minHeap.add(new int[]{num, i, 0});
    15             max = Math.max(max, num);
    16         }
    17         
    18         while(minHeap.size() == n){
    19             int [] cur = minHeap.poll();
    20             if(max - cur[0] < minLen){
    21                 minLen = max - cur[0];
    22                 res[0] = cur[0];
    23                 res[1] = max;
    24             }
    25             
    26             if(cur[2] < nums.get(cur[1]).size() - 1){
    27                 int num = nums.get(cur[1]).get(cur[2] + 1);
    28                 minHeap.add(new int[]{num, cur[1], cur[2] + 1});
    29                 max = Math.max(max, num);
    30             }
    31         }
    32         
    33         return res;
    34     }
    35 }
  • 相关阅读:
    jmeter接口自动化-读取CSV文件执行测试用例
    文件流下载excel表格
    如何查看死锁的表
    学习笔记
    当你需要验证数组是否都是0
    实验二
    centos8 https访问报错
    Linux命令常用搜集持续更新
    一文搞懂C语言中指针、数组、指针数组、数组指针、函数指针、指针函数
    11
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12114689.html
Copyright © 2011-2022 走看看