题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
https://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
package main /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @param k int整型 * @return int整型 */ func GetNumberOfK(nums []int, k int) int { // write code here l := binarySearch(nums, k) r := binarySearch(nums, k+1) if l == len(nums) || nums[l] != k { return 0 } return r - l } func binarySearch(nums []int, k int) int { l, r := 0, len(nums) for l < r { mid := (r-l)/2 + l if nums[mid] >= k { r = mid continue } l = mid + 1 } return l }