Smallest Range Covering Elements from K Lists Solutions in Go
Number 632
Difficulty Hard
Acceptance 52.5%
Link LeetCode
Other languages —
Solutions
Go solution by halfrost/LeetCode-Go
package leetcodeimport ("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.MaxInt64for 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].valres[0] = numList[left].valres[1] = numList[right].val}}freqMap[numList[left].index]--if freqMap[numList[left].index] == 0 {count--}left++}}return res}type element struct {val intindex int}type elements []element// Len definefunc (p elements) Len() int { return len(p) }// Swap definefunc (p elements) Swap(i, j int) { p[i], p[j] = p[j], p[i] }// SortByVal definetype SortByVal struct{ elements }// Less definefunc (p SortByVal) Less(i, j int) bool {return p.elements[i].val < p.elements[j].val}