website/content/ChapterFour/0600~0699/0632.Smallest-Range-Covering-Elements-from-K-Lists.md
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:
k <= 3500value of elements <= 10^5.你有 k 个升序排列的整数数组。找到一个最小区间,使得 k 个列表中的每个列表至少有一个数包含在其中。
我们定义如果 b-a < d-c 或者在 b-a == d-c 时 a < c,则区间 [a,b] 比 [c,d] 小。
注意:
package leetcode
import (
"math"
"sort"
)
func smallestRange(nums [][]int) []int {
numList, left, right, count, freqMap, res, length := []element{}, 0, -1, 0, map[int]int{}, make([]int, 2), math.MaxInt64
for i, ns := range nums {
for _, v := range ns {
numList = append(numList, element{val: v, index: i})
}
}
sort.Sort(SortByVal{numList})
for left < len(numList) {
if right+1 < len(numList) && count < len(nums) {
right++
if freqMap[numList[right].index] == 0 {
count++
}
freqMap[numList[right].index]++
} else {
if count == len(nums) {
if numList[right].val-numList[left].val < length {
length = numList[right].val - numList[left].val
res[0] = numList[left].val
res[1] = numList[right].val
}
}
freqMap[numList[left].index]--
if freqMap[numList[left].index] == 0 {
count--
}
left++
}
}
return res
}
type element struct {
val int
index int
}
type elements []element
// Len define
func (p elements) Len() int { return len(p) }
// Swap define
func (p elements) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
// SortByVal define
type SortByVal struct{ elements }
// Less define
func (p SortByVal) Less(i, j int) bool {
return p.elements[i].val < p.elements[j].val
}