1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 17:56:55 +02:00
LeetCode/go/relative-sort-array.go
Matej Focko d2ef757754
go: allow testing
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-06-16 11:44:08 +02:00

31 lines
443 B
Go

package main
import (
"cmp"
"slices"
)
func relativeSortArray(arr1 []int, arr2 []int) []int {
// remap the keys
keys := make(map[int]int, len(arr2))
for i, x := range arr2 {
keys[x] = i
}
// sort with the given keys
slices.SortFunc(arr1, func(x, y int) int {
xi, xFound := keys[x]
yi, yFound := keys[y]
if !xFound {
xi = 1000 + x
}
if !yFound {
yi = 1000 + y
}
return cmp.Compare(xi, yi)
})
return arr1
}