2021-6-16 日记 C++(三十五)

统计一个数字在排序数组中出现的次数。

示例 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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值