题目:统计一个数字在排序数组中出现的次数。
链接: 力扣Leetcode—剑指Offer—数组—53 - I. 在排序数组中查找数字 I.
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
思路:
法一Go代码:
package main
import "fmt"
func search(nums []int, target int) int {
m := make(map[int]int)
var res int
for _, v := range nums {
m[v]++
}
for key, v := range m {
if key == target {
res = v
}
}
return res
}
func main() {
a := []int{5, 7, 7, 8, 8, 10}
fmt.Println(search(a, 8))
}
提交截图:
法二Go代码:
package main
package main
import "fmt"
func search(nums []int, target int) int {
n := len(nums)
var res int
for i := 0; i < n; i++ {
if nums[i] == target {
res++
}
}
return res
}
func main() {
a := []int{5, 7, 7, 8, 8, 10}
fmt.Println(search(a, 8))
}
提交截图: