# 【Golang语言】LeetCode1122. Relative Sort Array

arr2 中的元素各不相同
arr2 中的每个元素都出现在 arr1 中

https://leetcode-cn.com/problems/relative-sort-array

``````输入：arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]

``````func relativeSortArray(arr1 []int, arr2 []int) []int {
maps := make(map[int]int, 0)
result := make([]int, 0)
for _, v := range arr1 {
maps[v]++
}
for _, v := range arr2 {
if times, ok := maps[v]; ok {
for i := 0; i < times; i++ {
result = append(result, v)
}
delete(maps, v)
}
}
keys := make([]int, 0)
for v := range maps {
keys = append(keys, v)
}
sort.Ints(keys)
for _, v := range keys {
times := maps[v]
for i := 0; i < times; i++ {
result = append(result, v)
}
}

return result
}
``````

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

arr2 中的元素各不相同
arr2 中的每个元素都出现在 arr1 中

https://leetcode-cn.com/problems/relative-sort-array

``````输入：arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]

``````func relativeSortArray(arr1 []int, arr2 []int) []int {
maps := make(map[int]int, 0)
result := make([]int, 0)
for _, v := range arr1 {
maps[v]++
}
for _, v := range arr2 {
if times, ok := maps[v]; ok {
for i := 0; i < times; i++ {
result = append(result, v)
}
delete(maps, v)
}
}
keys := make([]int, 0)
for v := range maps {
keys = append(keys, v)
}
sort.Ints(keys)
for _, v := range keys {
times := maps[v]
for i := 0; i < times; i++ {
result = append(result, v)
}
}

return result
}
``````