给两个排序好的整数数组,数组的长度是相同的,找到这两个数组的上中位数,也就是如果数组是偶数的话,输出前一个中位数。
时间复杂度O(logN),空间复杂度O(1)
public class UpMedian{ public static int getUpMedian(int[] arr1,int[] arr2) { if(arr1==null || arr1.length<=0 || arr2==null || arr2.length<=0) { System.out.println("Array is valid"); return -1; } if(arr1.length!=arr2.length) { System.out.println("Array length is valid"); return -1; } int start1 = 0; int end1 = arr1.length-1; int middle1 = 0; int start2 = 0; int end2 = arr2.length-1; int middle2 =0; //用来区分数组长度为奇偶数 int offset = 0; while(start1 < end1) { middle1 = (start1+end1)>>1; middle2 = (start2+end2)>>1; offset = ((end1-start1+1)&1)^1; if(arr1[middle1] > arr2[middle2]) { end1=middle1; start2=middle2+offset; } else if(arr1[middle1] < arr2[middle2]) { start1 = middle1 +offset; end2 = middle2; } else { return arr1[middle1]; } } return Math.min(arr1[start1], arr2[start2]); } public static void main(String[] args) { int[] a1 = {1,2,5,7}; int[] a2 = {2,3,8,10}; System.out.println(getUpMedian(a1, a2)); } }
这种题重在分析各种情况,
基本原理就是二分查找,但是你要确定你查找最合适的子数组,这样才能达到O(logN)的时间复杂度