题号:剑指 Offer 53 - I
题目名:在排序数组中查找数字 I
原题URL:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/
题目描述
统计一个数字在排序数组中出现的次数。
示例
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
限制
- 0 <= 数组长度 <= 50000
思路
1.二分找到target的值
2.找到值以后,往左右进行扫描
3.可能会把复杂度提升成O(N),如果有复杂度要求,就得继续二分
解题代码
class Solution {
public int search(int[] nums, int target) {
if(nums==null||nums.length==0) return 0;
//排序数组,那肯定是二分查找
int start = 0;
int end = nums.length-1;
int idx = -1;
int count = 0;
while (start<=end) {
int mid = start+(end-start)/2;
if(nums[mid] == target) {
count =1;
idx = mid;
break;
}else if (nums[mid] > target) {
//值在左边
end = mid-1;
}else {
start = mid+1;
}
}
if(count==0) return 0;
int right = idx+1;
int left = idx-1;
while (right <= nums.length-1) {
if(nums[right]==target) {
count++;
right++;
}else break;
}
while (left >=0 ) {
if(nums[left]==target) {
count++;
left--;
}else break;
}
return count;
}
}