编写Golang程序以查找数组中每个元素的出现次数
例子
输入数组=[1、3、4、3、2、3、4、0、2]
解决这个问题的方法
步骤1: 定义一个接受数组的方法。
步骤2: 定义一个映射,其中key将是数组的元素,起始值为0。
步骤3:开始迭代输入数组。如果映射中存在某个元素,则增加计数。
步骤4:如果映射中不存在该元素,则将其存储在映射中并使其值为1。
程序
package main
import (
"fmt"
)
func findFrequencyOfArray(arr []int){
frequency := make(map[int]int)
for _, item := range arr{
if frequency[item] == 0{
frequency[item] = 1
} else {
frequency[item]++
}
}
for item, count := range frequency{
fmt.Printf("%d occurring %d times.\n", item, count)
}
}
func main(){
findFrequencyOfArray([]int{2, 2, 5, 1, 3, 5, 0})
}输出结果
2 occurring 2 times. 5 occurring 2 times. 1 occurring 1 times. 3 occurring 1 times. 0 occurring 1 times.
热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练