题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
https://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
function GetNumberOfK(data, k) { // write code here if (data.length === 1 && data[0] === k) return 1 let left = 0 let right = data.length - 1 while (left <= right) { const mid = Math.floor((left + right) / 2) const midVal = data[mid] if (midVal < k) { left = mid + 1 } else if (midVal > k) { right = mid - 1 } else { let count = 1 let i = mid - 1 let j = mid + 1 while (data[i] === k) { count++ i-- } while (data[j] === k) { count++ j++ } return count } } return 0 } module.exports = { GetNumberOfK : GetNumberOfK };