剑指 Offer 53 - I. 在排序数组中查找数字 I(二分查找)
作者:互联网
剑指 Offer 53 - I. 在排序数组中查找数字 I
统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10]
, target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10]
, target = 6
输出: 0
提示:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums
是一个非递减数组-109 <= target <= 109
注意:本题与主站 34 题相同(仅返回值不同):https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
1 class Solution { 2 public: 3 int findRightBoundary(vector<int> &nums, int target) { 4 int left = 0; 5 int right = nums.size() - 1; 6 while (left <= right) { 7 int mid = left + (right - left) / 2; 8 if (nums[mid] <= target) { 9 left = mid + 1; 10 } else { 11 right = mid - 1; 12 } 13 } 14 return left; 15 } 16 int search(vector<int>& nums, int target) { 17 return findRightBoundary(nums, target) - findRightBoundary(nums, target - 1); 18 } 19 };
标签:target,nums,int,findRightBoundary,Offer,53,查找,数组 来源: https://www.cnblogs.com/MGFangel/p/16321443.html