1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| function GetNumberOfK (data, k) { let first = getFirst(data, k, 0, data.length - 1) let last = getLast(data, k, 0, data.length - 1) return first === -1 ? 0 : last - first + 1 }
function getFirst (arr, k, s, e) { if (s > e) return -1 let middle = (s + e) >> 1 if (arr[middle] > k) { return getFirst(arr, k, s, middle - 1) } else if (arr[middle] < k) { return getFirst(arr, k, middle + 1, e) } else if (middle - 1 >= s && arr[middle - 1] === k) { return getFirst(arr, k, s, middle - 1) } else { return middle } }
function getLast (arr, k, s, e) { if (s > e) return -1 let middle = (s + e) >> 1 if (arr[middle] > k) { return getLast(arr, k, s, middle - 1) } else if (arr[middle] < k) { return getLast(arr, k, middle + 1, e) } else if (middle + 1 <= e && arr[middle + 1] === k) { return getLast(arr, k, middle + 1, e) } else { return middle } }
|