统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路1
暴力解法,遍历整个数组,有重复的就count++,最后返回count
class Solution {
public:
int search(vector<int>& nums, int target) {
int count=0;
for(int x:nums)
{
if(x==target)count++;
}
return count;
}
};
思路2
二分法
1、首先通过二分法找到target在nums中的位置,标记为index
2、定义变量i为index-1,j为index+1,随后向数组两边遍历
3、其实跟暴力解法没啥区别,效率差不多…
class Solution {
public:
int search(vector<int>& nums, int target) {
int low=0 , high=nums.size()-1;
int mid=(low+high)/2;
int index=-1,count=0;
while(low<=high)
{
if(nums[mid]==target)
{
count=1;
index=mid;
break;
}
else if(nums[mid]>target)
{
high=mid-1;
mid=(low+high)/2;
}
else
{
low=mid+1;
mid=(low+high)/2;
}
}
if(index==-1)return 0;
int i=index-1,j=index+1;
while(i>0)
{
if(nums[i]==target)
{
count++;
}
i--;
}
if(i==0)
if(nums[i]==target)
{
count++;
}
while(j<nums.size()-1)
{
if(nums[j]==target)
{
count++;
}
j++;
}
if(j==nums.size()-1)
if(nums[j]==target)
{
count++;
}
return count;
}
};