Binary Search 专栏

Binary Search 时间复杂度 O(logN ), 因为每次减少一半 相当于取log

 

Q: 什么时候可以用Binary Seach?

A: 当数据是Sorted 并且支持Random Access的时候

 

Binary Search 的基本规则

1. 搜索空间在循环中不断减小

 The Searching Area decrease during the process

2. 目标元素(如果存在)不可以被排除到搜索空间之外 

 

Basic Binary Search 

 public int binarySearch(int[] array, int target) {
    //Corner case 
    if(array==null || array.length==0){
      return -1;
    }
    int left=0;
    int right=array.length-1;
    while(left<=right){
      int mid=left+(right-left)/2;
      if(array[mid]==target){
        return mid;
      }else if(array[mid]>target){
        right=mid-1;
      }else{
        left=mid+1;
      }
    }
    return -1;
  }

注意几点常见错误 

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

目的是防止Overflow 

 

2. 注意while 条件的判断 , 以下循环条件排列从苛刻到宽松 

(1).while(left<=right)

留下0个元素

(2).while(left<right)

留下1个元素

(3).while(left<right-1)

留下两个元素 

 

寻找最接近的元素index

 public int closest(int[] array, int target) {
    //Corner case 
    if(array==null || array.length==0){
      return -1;
    }
    int left=0;
    int right=array.length-1;
    while(left<right-1){
      int mid=left+(right-left)/2;
      if(array[mid]==target){
        return mid;
      }else if(array[mid]>target){
        //the right element may be the result
        //cannot be ruled out
        right=mid;
      }else{
        //the left element may be the result
        //cannot be ruled out
        left=mid;
      }
    }
    //Post processing 
    if(target-array[left]<array[right]-target){
      return left;
    }else{
      return right;
    }
  }

 

posted @ 2019-05-12 00:20  brooksLI  阅读(152)  评论(0编辑  收藏  举报