Leetcode Note: Go - Relative Sort Array

Relative Sort Array - LeetCode
https://leetcode.com/problems/relative-sort-array/

  • Go 言語で取り組んだメモ

回答

Go simple hehe - LeetCode Discuss
https://leetcode.com/problems/relative-sort-array/discuss/2469513/Go-simple-hehe

func relativeSortArray(arr1 []int, arr2 []int) []int {
    arr2Set := make([]int, 1001)
    
    for _, num := range arr2 {
        arr2Set[num]++
    }
    
    countMap := make([]int, 1001)
    
    var remainingArr []int
    
    for _, num := range arr1 {
        if arr2Set[num] == 0 {
            remainingArr = append(remainingArr, num)
        } else {
            countMap[num]++
        }
    }
    
    sort.Ints(remainingArr)
    
    var res []int
    
    for _, num := range arr2 {
        for i := 0; i < countMap[num]; i++ {
            res = append(res, num)
        }
    }
    
    res = append(res, remainingArr...)
    
    return res
}