有一个已经排序的数组(升序),数组中可能有正数、负数或0,求数组中元素的绝对值最小的数,要求,不能用顺序比较的方法(复杂度需要小于O(n)),可以使用任何语言实现。
AbsSmall.java
public class AbsSmall { public int Bsearch(int[] arr) { int low=0; int high=arr.length-1; return Bsearch2(arr,low,high); } public int Bsearch2(int arr[],int low,int high) { int mid; if(arr[low]>=0) return arr[low]; else if(arr[high]<=0) return arr[high]; while(low<=high) { mid=(low+high)/2; if(arr[mid]==0) return 0; else if(arr[mid]<0) { if(arr[mid+1]>=0) return Math.abs(arr[mid])>arr[mid+1]?arr[mid+1]:arr[mid]; else return Bsearch2(arr,mid+1,high); } else { if(arr[mid-1]<=0) return Math.abs(arr[mid-1])>arr[mid]?arr[mid]:arr[mid-1]; else return Bsearch2(arr,low,mid-1); } } return 0; } }
AbsSmallClient.java
public class AbsSmallClient { public static void main(String[] args) { int[] arr={-20,-13,-4,3,77,200}; System.out.println(new AbsSmall().Bsearch(arr)); } }