Created
February 28, 2018 21:00
-
-
Save nleiva/09faa7dc38ddc186582978286ef9ff2f to your computer and use it in GitHub Desktop.
SHORTEST RANGE IN K SORTED LISTS from https://www.youtube.com/watch?v=zplklOy7ENo, first take (not optimal)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sort" | |
) | |
type Slice []int | |
func (a Slice) Len() int { return len(a) } | |
func (a Slice) Swap(i, j int) { a[i], a[j] = a[j], a[i] } | |
func (a Slice) Less(i, j int) bool { return a[i] < a[j] } | |
func validRange(x, y int, k [][]int) (b bool) { | |
b = true | |
for _, v := range k { | |
for _, v := range v { | |
if (x <= v) && (v <= y) { | |
break | |
} | |
if v >= y { | |
b = false | |
break | |
} | |
} | |
} | |
return b | |
} | |
func joinSlice(k [][]int) []int { | |
s := Slice{} | |
for _, v := range k { | |
s = append(s, v...) | |
} | |
sort.Sort(s) | |
return s | |
} | |
func computeRanges(a []int, n int) (k [][]int) { | |
for i := 0; i < len(a)-1; i++ { | |
for j := i; j < len(a)-1; j++ { | |
if j-i <= n { | |
k = append(k, []int{a[i], a[j+1]}) | |
} | |
} | |
} | |
return k | |
} | |
func main() { | |
k1 := []int{4, 10, 15, 24} | |
k2 := []int{0, 9, 19, 20} | |
k3 := []int{5, 18, 22, 30} | |
k := [][]int{k1, k2, k3} | |
// Create a single slice | |
singleSlice := joinSlice(k) | |
// Compute all the ranges up to len(k) indexes away. | |
ranges := computeRanges(singleSlice, len(k)) | |
// Determine all ranges that cover elements in all slices. | |
kf := []int{} | |
min := singleSlice[len(singleSlice)-1] | |
// Find the min range. | |
for _, v := range ranges { | |
if validRange(v[0], v[1], k) && (v[1]-v[0] < min) { | |
min = v[1] - v[0] | |
kf = v | |
} | |
} | |
fmt.Printf("Result: %v\n", kf) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment