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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

采用二分法,分别找到等于目标数的最小索引值和最大索引值,之后做差。

    public int search(int[] nums, int target) {
        if (nums.length == 0 || nums[0] > target || nums[nums.length - 1] < target) {
            return 0;
        }
        int min = getMin(nums, target);
        int max = getMax(nums, target);
        return max - min + 1;
    }

    private int getMin (int[] nums, int target) {
        int st = 0;
        int end = nums.length - 1;
        while (st < end) {
            int m = st + ((end - st) >> 1);
            if (nums[m] < target) {
                st = m + 1;
            } else {
                end = m;
            }
        }
        return st;
    }

    private int getMax (int[] nums, int target) {
        int st = 0;
        int end = nums.length - 1;
        while (st < end) {
            int m = st + ((end - st + 1) >> 1);
            if (nums[m] > target) {
                end = m - 1;
            } else {
                st = m;
            }
        }
        return st;
    }

posted @ 2021-05-08 17:56  旺仔古李  阅读(48)  评论(0编辑  收藏  举报