編寫一個 Golang 程式來查詢陣列中某個元素的頻率


示例

在輸入陣列中,arr = [2, 4, 6, 7, 8, 1, 2]

給定陣列中 2 的頻率為 2

7 的頻率為 1

3 的頻率為 0。

解決這個問題的方法

步驟 1:定義一個接受陣列和 num 的函式

步驟 2:宣告一個變數 count = 0

步驟 3:迭代給定的陣列,如果 num 在陣列中出現,則將 count 加 1。

步驟 4:為給定的 num 列印 count

程式

即時演示

package main
import "fmt"
func findFrequency(arr []int, num int){
   count := 0
   for _, item := range arr{
      if item == num{
         count++
      }
   }
   fmt.Printf("Frequency of %d in given array is %d.\n", num, count)
}

func main(){
   findFrequency([]int{2, 4, 5, 6, 3, 2, 1}, 2)
   findFrequency([]int{0, 1, 3, 1, 6, 2, 1}, 1)
   findFrequency([]int{1, 2, 3, 4, 5, 6, 7}, 10)
}

輸出

Frequency of 2 in given array is 2.
Frequency of 1 in given array is 3.
Frequency of 10 in given array is 0.

更新於:2021 年 2 月 4 日

239 次瀏覽

開始您的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.