632 Smallest Range

1. Question

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

We define the range [a,b] is smaller than range [c,d] ifb-a < d-cora < cifb-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. -10^5 <=value of elements<= 10^5.

2. Implementation

(1) Two Pointers + HashMap

思路:这题可以转换成Minimum Size Substring来做,首先建立一个list存储每个数和这个数所在的list的id,然后按照数的大小对list排序。接下来的做法就和Minimum Size Substring一样,维护一个Sliding Window,当这个window包含所有list的id时,则更新start pointer,结果即可

(2) Heap

3. Time & Space Complexity

Two Pointers + HashMap: 时间复杂度O(nlogn), 空间复杂度O(nk), n为nums的size, k为每个nums的平均元素个数

Heap: 时间复杂度O(nklogn), 空间复杂度O(n)

Last updated

Was this helpful?