Skip to content

Instantly share code, notes, and snippets.

@nleiva
Created March 1, 2018 03:28
Show Gist options
  • Save nleiva/8ee116350b1d966075362f6bb997f48b to your computer and use it in GitHub Desktop.
Save nleiva/8ee116350b1d966075362f6bb997f48b to your computer and use it in GitHub Desktop.
SHORTEST RANGE IN K SORTED LISTS from https://www.youtube.com/watch?v=zplklOy7ENo, solution explained in the video
package main
import (
"container/heap"
"fmt"
)
type mHeap struct {
value int
array int
}
type minHeap []mHeap
func (m minHeap) Len() int { return len(m) }
func (m minHeap) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
func (m minHeap) Less(i, j int) bool { return m[i].value < m[j].value }
func (m *minHeap) Push(x interface{}) {
*m = append(*m, x.(mHeap))
}
func (m *minHeap) Pop() interface{} {
old := *m
n := len(old)
x := old[n-1]
*m = old[0 : n-1]
return x
}
type maxHeap []mHeap
func (m maxHeap) Len() int { return len(m) }
func (m maxHeap) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
func (m maxHeap) Less(i, j int) bool { return m[i].value > m[j].value }
func (m *maxHeap) Push(x interface{}) {
*m = append(*m, x.(mHeap))
}
func (m *maxHeap) Pop() interface{} {
old := *m
n := len(old)
x := old[n-1]
*m = old[0 : n-1]
return x
}
func main() {
k0 := []int{4, 10, 15, 24}
k1 := []int{0, 9, 12, 20}
k2 := []int{5, 18, 22, 30}
k := [][]int{k0, k1, k2}
x, y, z := 0, 0, 0
indexes := []int{x, y, z}
minRange := 1000
minRangeMin := 0
minRangeMax := 0
// Initialize our heaps.
minH := &minHeap{}
maxH := &maxHeap{}
heap.Init(minH)
heap.Init(maxH)
// Add first values
for i := range k {
heap.Push(minH, mHeap{k[i][indexes[i]], i})
heap.Push(maxH, mHeap{k[i][indexes[i]], i})
}
for {
// Pop values from heaps
pMin := heap.Pop(minH)
pMax := heap.Pop(maxH)
// restore the max
heap.Push(maxH, pMax)
// Grab current values
min := pMin.(mHeap).value
max := pMax.(mHeap).value
Range := max - min
// Store values if this is the minimum range so far.
if Range < minRange {
minRange = Range
minRangeMin = min
minRangeMax = max
}
// Find out the index of the min value
i := pMin.(mHeap).array
// Increment this index
indexes[i]++
// If we reached the end of one of the lists.
if indexes[i] >= len(k[i]) {
break
}
// Add new elements to the heap
heap.Push(minH, mHeap{k[i][indexes[i]], i})
heap.Push(maxH, mHeap{k[i][indexes[i]], i})
}
fmt.Printf("Min: %v\n", minRangeMin)
fmt.Printf("Max: %v\n", minRangeMax)
fmt.Printf("Result: %v\n", minRange)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment