赞
踩
仅供学习
二分查找算法,时间复杂度为 O(log(min(m, n))),其中 m 和 n 分别是两个数组的长度。
int max(int a, int b) {
return a > b ? a : b;
}
int min(int a, int b) {
return a < b ? a : b;
}
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) { // Ensure nums1 is the smaller array if (nums1Size > nums2Size) { return findMedianSortedArrays(nums2, nums2Size, nums1, nums1Size); } int x = nums1Size; int y = nums2Size; int low = 0; int high = x; while (low <= high) { int partitionX = (low + high) / 2; int partitionY = (x + y + 1) / 2 - partitionX; int maxX = (partitionX == 0) ? INT_MIN : nums1[partitionX - 1]; int minX = (partitionX == x) ? INT_MAX : nums1[partitionX]; int maxY = (partitionY == 0) ? INT_MIN : nums2[partitionY - 1]; int minY = (partitionY == y) ? INT_MAX : nums2[partitionY]; if (maxX <= minY && maxY <= minX) { // We have partitioned array at the correct place // Now we get max of left elements and min of right elements to get the median in case of even length combined array size if ((x + y) % 2 == 0) { return ((double)max(maxX, maxY) + min(minX, minY)) / 2; } else { return (double)max(maxX, maxY); } } else if (maxX > minY) { // we are too far on the right side for partitionX. Go on left side. high = partitionX - 1; } else { // we are too far on the left side for partitionX. Go on right side. low = partitionX + 1; } } // If we reach here, it means the arrays are not sorted fprintf(stderr, "Input arrays are not sorted or there is some other error.\n"); return -1; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。