go: add «2948. Make Lexicographically Smallest Array by Swapping Elements»

URL:	https://leetcode.com/problems/make-lexicographically-smallest-array-by-swapping-elements/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-01-25 23:39:54 +01:00
parent 3c9810e7de
commit a67853e75f
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,45 @@
package main
import (
sll "github.com/emirpasic/gods/v2/lists/singlylinkedlist"
"slices"
)
func lexicographicallySmallestArray(nums []int, limit int) []int {
// sort the numbers
sortedNums := slices.Clone(nums)
slices.Sort(sortedNums)
// assign groups
numToGroup := make(map[int]int)
groups := make(map[int]*sll.List[int])
group := 0
for i, x := range sortedNums {
if i > 0 && sortedNums[i]-sortedNums[i-1] > limit {
group++
}
lst, ok := groups[group]
if !ok {
lst = sll.New[int]()
groups[group] = lst
}
numToGroup[x] = group
lst.Append(x)
}
// emplace into original slice
for i, originalX := range nums {
group = numToGroup[originalX]
lst, _ := groups[group]
newX, _ := lst.Get(0)
lst.Remove(0)
nums[i] = newX
}
return nums
}