One minute
Leetcode 1331
1331. Rank Transform of an Array
The idea of this solution is to:
- Copy
arr
. - Then sort the copy
- Then loop through the copy and add all the values and indexes of the copy to a map called
m
. - Then loop through
0
tolen(arr) - 1
, and makearr[i] = m[arr[i]]
. - Then return
arr
.
func arrayRankTransform(arr []int) []int {
g := make([]int, len(arr))
m := make(map[int]int)
counter := 1
copy(g, arr)
sort.Ints(g)
for i := range g {
if i >= 1 && g[i] == g[i-1] {
counter -= 1
}
m[g[i]] = counter
counter++
}
for i := range arr {
arr[i] = m[arr[i]]
}
return arr
}
Read other posts