系列文章目录
前言
一、剑指 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 <= 数组长度 <= 50000
注意:本题与主站 34 题相同(仅返回值不同):https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
相关标签
数组
二分查找
二、使用步骤
1.引入库
代码如下:
自己码出来的笨方法
时间复杂度为N
class Solution {
public:
int search(vector<int>& nums, int target) {
int n=0;
for(int num:nums)
{
if(num == target) n++;
}
return n;
}
};
二分法
时间复杂度为logN
class Solution {
public:
int search(vector<int>& nums, int target) {
return findRightBoundary(nums, target) - findRightBoundary(nums, target-1);
}
private:
int findRightBoundary(vector<int> &nums, int tar)
{
int i =0, j=nums.size()-1;
while( i <=j)
{
int m =(i+j)/2;
if(nums[m] <= tar) i = m+1;
else j=m-1;
}
return i;
}
};
总结
以上就是今天要讲的内容