题解 | #数字在升序数组中出现的次数# | C++
数字在升序数组中出现的次数
https://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型vector * @param k int整型 * @return int整型 */ int GetNumberOfK(vector<int>& nums, int k) { int pos = -1; int l = 0, r = nums.size() - 1; while (l <= r) { int mid = l + (r - l); if (nums[mid] == k) { pos = mid; break; } else if (nums[mid] > k) { r = mid - 1; } else { l = mid + 1; } } if (pos == -1) return 0; int cnt = 1; r = pos+1; l = pos-1; while (r < nums.size()) { if (nums[r] == k) cnt++; else break; r++; } while (l >= 0) { if (nums[l] == k) cnt++; else break; l--; } return cnt; } };