二分变形之排序数组查找数字次数

二分变形之排序数组查找数字次数_第1张图片
思路:

  • 找左边界,找右边界,做差。
class Solution {
    public int search(int[] nums, int target) {
        int res = 0;
        int l = 0,r = nums.length-1;
        while(l<=r){//找左边界(其实可以找出左边界,顺着往后计数,也可以做,但是效率低一点)
            int mid = l+(r-l)/2;
            if(nums[mid]>=target){
                r = mid-1;
            }else{
                l = mid+1;
            }
        }
        int start = l;//记录
        //归零
        l = 0;
        r = nums.length-1;
        while(l<=r){//找右边界
            int mid = l+(r-l)/2;
            if(nums[mid]<=target){
                l = mid+1;
            }else{
                r = mid-1;
            }
        }
        int end = r;
        return end-start+1;
    }
}

优化一下:

  • 找右边界
  • 左边界其实就是target-1的右边界
class Solution {
    public int search(int[] nums, int target) {
        return findRight(nums,target)-findRight(nums,target-1);
    }
    public int findRight(int[] nums,int t){//封装函数找右边界
        int l = 0,r = nums.length-1;
        while(l<=r){
            int mid = (r+l)/2;
            if(nums[mid]<=t){
                l = mid+1;
            }else{
                r = mid-1;
            }
        }
        return r;
    }
}

你可能感兴趣的:(LeetCode)