码迷,mamicode.com
首页 > 其他好文 > 详细

搞懂二分查找

时间:2021-03-31 11:46:55      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:static   else   arch   循环   bin   while   一个   退出   return   

class Solution {
    public static void main(String[] args) {
        int[] arr = new int[]{0, 1, 2, 2, 2, 3, 4, 5};
        //int index = binarySearch(arr, 2);
        //int index2 = leftBound(arr, 2);
        int index3 = rightBound(arr, 2);
        //System.out.println(index + ":" + arr[index]);
        //System.out.println(index2 + ":" + arr[index2]);
        System.out.println(index3 + ":" + arr[index3]);
    }

    public static int binarySearch(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        return -1;
    }
    
    /*
    * 找左边界和找右边界都有一个退出while循环的情况,即[left==right+1,right]
    * 所以:
    * 如果找左边界,返回left
    * 如果找右边界,返回right
    * 当然:
    * 返回之前,需要判断left或者right是否越界,即:left>=num.length和right<0
    * 并且判断nums[left/right] 是否等于 target 
    * */
    
    public static int leftBound(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        if (left >= nums.length || nums[left] != target)
            return -1;
        return left;
    }

    public static int rightBound(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                left = mid + 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        if (right < 0 || nums[right] != target)
            return -1;
        return right;
    }

}

搞懂二分查找

标签:static   else   arch   循环   bin   while   一个   退出   return   

原文地址:https://www.cnblogs.com/zyk98/p/14594788.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!