Leetcode 刷题

剑指 Offer 53 - I. 在排序数组中查找数字 I

  • 难度:简单

题目

统计一个数字在排序数组中出现的次数。

相同题目: https://leetcode-cn.com/problems/min-stack/

示例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 <= $10^5$

  • $-10^9$ <= nums[i] <= $10^9$

  • nums 是一个非递减数组

  • $-10^9$ <= target <= $10^9$

注意:本题与主站 34 题相同(仅返回值不同):https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

class Solution {
public:
int search(vector<int>& nums, int target) {
if(!nums.size()) return 0;
int right = nums.size() - 1;
int left = 0;
while(left < right){
int mid = left + (right - left) / 2;
if(nums[mid] >= target){
right = mid;
}else if(nums[mid] < target){
left = mid + 1;
}
}
if(nums[right] != target) return 0;
int begin = right;
left = 0, right = nums.size() -1;
while(left < right){
int mid = left + (right - left + 1) / 2;
if(nums[mid] <= target){
left = mid;
}else{
right = mid - 1;
}
}
int end = right;
return end - begin + 1;
}
};

思路

  1. 二分查找

  2. 二分讲解详细讲解