Leetcode Note: Go - Most Frequent Number Following Key in an Array

Most Frequent Number Following Key In an Array - LeetCode
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/

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

回答

Go one pass - Most Frequent Number Following Key In an Array - LeetCode
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/solutions/2213533/go-one-pass/

func mostFrequent(nums []int, key int) int {
    res, max, d := 0, 0, make(map[int]int)
    
    for i := 1; i < len(nums); i++ {
        if nums[i - 1] == key {
            target := nums[i]
            
            d[target]++
            
            if d[target] > max {
                max = d[target]
                res = target
            }
        }
    }
    
    return res
}