Leetcode Note: Go - Degree of an Array
Degree of an Array - LeetCode
https://leetcode.com/problems/degree-of-an-array/
- Go 言語で取り組んだメモ
所感
- 負ではない整数 nums 配列が与えられるので、最大頻度を求める
- 配列と同じ次数 (degree) を持つ nums の連続した細部配列の最小の長さを int で return する
回答
Degree of an Array - LeetCode
https://leetcode.com/problems/degree-of-an-array/solution/
Golang O(n) solution - LeetCode Discuss
https://leetcode.com/problems/degree-of-an-array/discuss/1168066/Golang-O(n)-solution
func findShortestSubArray(nums []int) int {
res := 1
starts := make(map[int]int)
counters, maxCounter := make(map[int]int), 1
for i, num := range nums {
if _, ok := starts[num]; ok {
counters[num]++
if counters[num] > maxCounter {
maxCounter = counters[num]
res = i - starts[num] + 1
} else if counters[num] == maxCounter && i - starts[num] < res {
res = i - starts[num] + 1
}
} else {
starts[num], counters[num] = i, 1
}
}
return res
}