这个分段有序的数组是由一个有序数组变化而来的,变化规则是:随机在有序数组中找一个索引i,将a[0]-a[i]移动到a[n]后面。
也就是将有序数组A[n],形式为:a[0]...a[i],a[i+1]...a[n] 变成分段有序数组B[n],形式为:a[i+1]...a[n],a[0]...a[i] 。
public static boolean getB(int[] a,int x){ if(null ==a|| a.length ==0){ return false; } int to = a.length-1; int from =0; int mid = (to+from)/2; while (from <= to && from < a.length && to < a.length && from >=0) { mid = (to+from)/2; if(a[mid] == x){ return true; }else if(a[mid] > x ){ if( (mid-1) >=0 && a[mid] < a[mid-1]){ return false; } to =mid-1; }else if(a[mid] < x){ if( (mid+1) < a.length-1 && a[mid] > a[mid+1]){ return false; } if(x ==a[to]){ return true; }else if (x > a[to]){ to = mid -1; }else { from = mid+1; } } } return false; }
要求时间复杂度尽可能低