Update 53. 数字在排序数组中出现的次数.md

题目链接改为力扣中的对应题目,题目描述和代码按该题的接口调整。
This commit is contained in:
CyC2018
2026-10-28 13:45:06 +08:00
parent b259c3883c
commit 54c2d3a337
@@ -2,7 +2,7 @@
## 题目链接
[牛客网](https://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2?tpId=13&tqId=11190&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
[Leetcode](https://leetcode.cn/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/)
## 题目描述
@@ -41,11 +41,11 @@ public int binarySearch(int[] nums, int K) {
但是在查找第一个位置时,找到元素之后应该继续往前找。也就是当 nums[m]\>=k 时,在左区间继续查找,左区间应该包含 m 位置。
```java
private int binarySearch(int[] nums, int K) {
private int binarySearch(int[] nums, int target) {
int l = 0, h = nums.length;
while (l < h) {
int m = l + (h - l) / 2;
if (nums[m] >= K)
if (nums[m] >= target)
h = m;
else
l = m + 1;
@@ -57,10 +57,22 @@ private int binarySearch(int[] nums, int K) {
查找最后一个位置可以转换成寻找 k+1 的第一个位置,并再往前移动一个位置。
```java
public int GetNumberOfK(int[] nums, int K) {
int first = binarySearch(nums, K);
int last = binarySearch(nums, K + 1);
return (first == nums.length || nums[first] != K) ? 0 : last - first;
public int countTarget(int[] scores, int target) {
int first = binarySearch(scores, target);
int last = binarySearch(scores, target + 1);
return (first == scores.length || scores[first] != target) ? 0 : last - first;
}
private int binarySearch(int[] nums, int target) {
int l = 0, h = nums.length;
while (l < h) {
int m = l + (h - l) / 2;
if (nums[m] >= target)
h = m;
else
l = m + 1;
}
return l;
}
```