From 1e48c99bfbf1edf03ccf354bb2fef50900186691 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 11 Jun 2024 22:20:18 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB1122.=20Relative=20Sort=20Arr?= =?UTF-8?q?ay=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- go/relative-sort-array.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 go/relative-sort-array.go diff --git a/go/relative-sort-array.go b/go/relative-sort-array.go new file mode 100644 index 0000000..82590ed --- /dev/null +++ b/go/relative-sort-array.go @@ -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 +}