website/content/ChapterFour/1100~1199/1122.Relative-Sort-Array.md
Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.
Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in arr2 should be placed at the end of arr1 in ascending order.
Example 1:
Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
Output: [2,2,2,1,4,3,3,9,6,7,19]
Constraints:
arr1.length, arr2.length <= 10000 <= arr1[i], arr2[i] <= 1000arr2[i] is distinct.arr2[i] is in arr1.给你两个数组,arr1 和 arr2,
对 arr1 中的元素进行排序,使 arr1 中项的相对顺序和 arr2 中的相对顺序相同。未在 arr2 中出现过的元素需要按照升序放在 arr1 的末尾。
提示:
package leetcode
import "sort"
// 解法一 桶排序,时间复杂度 O(n^2)
func relativeSortArray(A, B []int) []int {
count := [1001]int{}
for _, a := range A {
count[a]++
}
res := make([]int, 0, len(A))
for _, b := range B {
for count[b] > 0 {
res = append(res, b)
count[b]--
}
}
for i := 0; i < 1001; i++ {
for count[i] > 0 {
res = append(res, i)
count[i]--
}
}
return res
}
// 解法二 模拟,时间复杂度 O(n^2)
func relativeSortArray1(arr1 []int, arr2 []int) []int {
leftover, m, res := []int{}, make(map[int]int), []int{}
for _, v := range arr1 {
m[v]++
}
for _, s := range arr2 {
count := m[s]
for i := 0; i < count; i++ {
res = append(res, s)
}
m[s] = 0
}
for v, count := range m {
for i := 0; i < count; i++ {
leftover = append(leftover, v)
}
}
sort.Ints(leftover)
res = append(res, leftover...)
return res
}