【剑指offer】面试题53 - 1:在排序数组中查找数字 I(java)

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

 

示例 1:

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

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

限制:

0 <= 数组长度 <= 50000

 

代码:

class Solution {

    public int search(int[] nums, int target) {

        if(nums.length==0)

        {

            return 0;

        }

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

        int mid = left +(right-left)/2;

        while(left

        {

            mid = left+(right-left)/2;

            if(nums[mid]

            {

                left = mid + 1;

            }

            else

            {

                right = mid;

            }

        }

        int a = left;

        left = 0;

        right = nums.length-1;

        while(left

        {

            mid = (right-left)/2+left;

            if(nums[mid]<=target)

            {

                left = mid+1;

            }

            else{

                right = mid;

            }

        }

        if(nums[right]==target)

        {

            return right- a+1;

        }

        else

        {

            return right - a;

        }

    }

}

你可能感兴趣的:(剑指offer)