首页 > 代码库 > 新手算法学习之路----二分法Search-for-a-Range

新手算法学习之路----二分法Search-for-a-Range

题目:给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。

          如果目标值不在数组中,则返回[-1, -1]

思路:如果中点等于target就要分为两部分来查找,中点的左右部分分别来找第一个和最后一个target值;左边,只考虑mid值小于和等于target值;右边只考虑mid值大于和等于target值

public static int[] searchRange(int[] A, int target) {
           int start=0, end = A.length-1;
           int mid,left_position=-1,right_position=-1;
           int result[] = {left_position,right_position};
           if(A.length == 0) return result;
             while(start<end-1){
                  mid = start+(end-start)/2;
                  if(A[mid]<target){
                     start = mid +1;
                  }else if(A[mid]>target){
                     end = mid-1;
                  }else{
                   left_position=Search_Middle_left(A, start, mid-1,target);
                   right_position=Search_Middle_right(A, mid+1, end,target);
                   break;
                  }
             }
              //int []resualt={left_position,right_position};
              //return resualt;      
              return new int[]{left_position,right_position};
    }
public static int Search_Middle_right(int[] A, int low, int high,int target){ int this_low = low, this_high=high; int mid; while(this_low+1<this_high){ mid = this_low+(this_high-this_low)/2;//在上一个中点的左边找target值,左边是不可能有元素值小于target 所以只讨论 等于 和大于的时候 if(A[mid]==target){ //target值等于mid的时候,继续往序列的左边找, this_low = mid; //当中间值等于target时候,如果要往右继续寻找,就必须从mid的那个位置开始,如果从mid-1,那么如果从mid-1位置就大于target,那么程序就要出错了 }else if(A[mid]>target){ //target值小于mid的时候,往mid的右边找 this_high = mid -1; } } if(A[this_low]==target) return this_low; else return this_high; } public static int Search_Middle_left(int[]A, int low ,int high, int target){ int this_low = low, this_high=high; int mid; while(this_low+1<this_high){ // 当中间值等于target值的时候在左边部分找,左边部分不能有大于target的值,所以不考虑A[mid]>target的时候 mid = this_low+(this_high-this_low)/2; if(A[mid]==target){ // 中间值等于target的时候继续往左找 this_high = mid; }else if(A[mid]<target) { //如果中间值小于target值的时候,就往右找 this_low = mid +1; } } if(A[this_high]==target) return this_high; else return this_low; }

 

新手算法学习之路----二分法Search-for-a-Range