53.在排序数组中查找数字 I

面试题53 - I. 在排序数组中查找数字 I

难度简单23

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

示例 1:

输入: nums = [5,7,7,8,8,10], target = 8
输出: 2

示例 2:

输入: nums = [5,7,7,8,8,10], target = 6
输出: 0

1.二分查找

//search问题 先O(n)>二分
//思路 使用二分查找右边界 和 左边界 right-left-1
//time : O(logn)
//space : O(1)
public int search(int[] nums, int target) {
    int i = 0,j = nums.length-1;
    while(i<=j){
        int m = (i+j)/2;
        if(nums[i]<=target) i = m + 1;
        else 
            j = m-1;
    }
    // target is right index 
    int right = i;

    i = 0;j = nums.length-1;
    while(i<=j){
        int m = (i+j)/2;
        if(nums[i]<target) i = m+1;
        else 
            j = m-1;
    }
    // target is left index
    int left = j;
    return right-left-1;
}