4 Star 25 Fork 18

编程语言算法集 / Go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
mode.go 773 Bytes
一键复制 编辑 原始数据 按行查看 历史
Taj 提交于 2022-09-23 09:44 . feat: re-enable all linters (#541)
// mode.go
// author(s): [CalvinNJK] (https://github.com/CalvinNJK)
// description: Finding Mode Value In an Array
// see mode.go
package math
import (
"errors"
"github.com/TheAlgorithms/Go/constraints"
)
// ErrEmptySlice is the error returned by functions in math package when
// an empty slice is provided to it as argument when the function expects
// a non-empty slice.
var ErrEmptySlice = errors.New("empty slice provided")
func Mode[T constraints.Number](numbers []T) (T, error) {
countMap := make(map[T]int)
n := len(numbers)
if n == 0 {
return 0, ErrEmptySlice
}
for _, number := range numbers {
countMap[number]++
}
var mode T
count := 0
for k, v := range countMap {
if v > count {
count = v
mode = k
}
}
return mode, nil
}
Go
1
https://gitee.com/TheAlgorithms/Go.git
git@gitee.com:TheAlgorithms/Go.git
TheAlgorithms
Go
Go
master

搜索帮助