剑指 Offer 53 - I. 在排序数组中查找数字 I
剑指 Offer 53 - I. 在排序数组中查找数字 I
题目
链接
https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/
问题描述
统计一个数字在排序数组中出现的次数。
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums 是一个非递减数组
-109 <= target <= 109
示例
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
提示
思路
递增数组,找到某个数的出现次数,那么用二分查找找到左右边界,直接计算即可。
复杂度分析
时间复杂度 O(logn)
空间复杂度 O(1)
代码
Java
public static int search(int[] nums, int target) {
if (nums.length == 0) {
return 0;
}
int left = 0, right = nums.length - 1;
//左边界
while (left <= right) {
int mid = left + (right - left) / 2;
if(nums[mid] > target){
right = mid - 1;
}else if(nums[mid] < target){
left = mid + 1;
}else if(nums[mid] == target){
right = mid - 1;
}
}
int ans = left;
//右边界
left = 0; right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if(nums[mid] > target){
right = mid - 1;
}else if(nums[mid] < target){
left = mid + 1;
}else if(nums[mid] == target){
left = mid + 1;
}
}
ans = right - ans + 1;
return ans;
}