剑指 Offer 53 - I. 在排序数组中查找数字 I(二分查找)

package com.heu.wsq.leetcode.inoffer;

/**
 * 剑指 Offer 53 - I. 在排序数组中查找数字 I
 * @author wsq
 * @date 2021/4/24
 * 统计一个数字在排序数组中出现的次数。
 *
 * 示例 1:
 * 输入: nums = [5,7,7,8,8,10], target = 8
 * 输出: 2
 *
 * 示例 2:
 * 输入: nums = [5,7,7,8,8,10], target = 6
 * 输出: 0
 *
 * 链接:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof
 */
public class Offer53 {
    private int target;

    public int search(int[] nums, int target) {
        if(nums == null || nums.length == 0){
            return 0;
        }
        this.target = target;

        int left = 0;
        int right = nums.length - 1;

        int count = search(nums, left, right);
        return count;
    }

    /**
     * 递归的方式实现二分查找
     * @param nums
     * @param left
     * @param right
     * @return
     */
    public int search(int[] nums, int left, int right){
        if(left > right){
            return 0;
        }
        int count = 0;
        int mid = (left + right) >> 1;
        if(nums[mid] == this.target){
            count++;
            count += search(nums, left, mid - 1);
            count += search(nums, mid + 1, right);
        }else if(nums[mid] < this.target){
            count += search(nums, mid + 1, right);
        }else{
            count += search(nums, left, mid - 1);
        }
        return count;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值