mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
go: add «1122. Relative Sort Array»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
6a3f0058c0
commit
1e48c99bfb
1 changed files with 31 additions and 0 deletions
31
go/relative-sort-array.go
Normal file
31
go/relative-sort-array.go
Normal file
|
@ -0,0 +1,31 @@
|
||||||
|
package relative_sort_array
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
Loading…
Reference in a new issue