【LeetCode刷题】剑指 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)根据二分查找,我们先判断中间的数是不是目标数target:如果是,则在其左右检索,看还有没有相等的数,并统计个数;

(2)如果不是,就分别在左右进行二分查找。

(3)代码

class Solution {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length;

        int count = 0;                      //计数

        while(left<right){
            int mid = (left+right)/2;
            if(nums[mid]==target){           //相等
                int l = mid;
                int r = mid;
                while(l>=0&&nums[l]==target){
                    l--;
                    count++;
                }
                while(r<nums.length&&nums[r]==target){
                    r++;
                    count++;
                }
                return count-1;              //多统计了一次
            }else if(nums[mid]>target){      //中间值大,查找区间在左侧
                right = mid;
            }else{
                left=mid+1;
            }
        }
        return count;
    }
}


参考:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值