剑指offer53-1 在排序数组中查找数字
题目
统计一个数字在排序数组中出现的次数。
示例 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⁵
-10⁹ <= nums[i] <= 10⁹
nums 是一个非递减数组
-10⁹ <= target <= 10⁹
方法
遍历法
- 时间复杂度:O(n),n为数组的长度
- 空间复杂度:O(1)
class Solution {
public int search(int[] nums, int target) {
int res = 0;
for(int i=0;i<nums.length;i++){
if(target==nums[i]){
res++;
}
if(res>0&&target!=nums[i]){
break;
}
}
return res;
}
}
二分法
- 时间复杂度:O(logn),n为数组的长度
- 空间复杂度:O(1)