|
7 | 7 | public class MedianOfTwoSortedArrays {
|
8 | 8 |
|
9 | 9 | public double findMedianSortedArrays(int[] nums1, int[] nums2) {
|
10 |
| - // 从左(小值)开始记录数 |
11 |
| - int leftNum = Integer.MIN_VALUE; |
12 |
| - // 从右(大值)开始记录数 |
13 |
| - int rightNum = Integer.MAX_VALUE; |
| 10 | + int m = nums1.length; |
| 11 | + int n = nums2.length; |
| 12 | + int left = (m + n + 1) / 2; |
| 13 | + int right = (m + n + 2) / 2; |
14 | 14 |
|
15 |
| - // 数组1左(小值)索引 |
16 |
| - int nums1Left = 0; |
17 |
| - // 数组2左(小值)索引 |
18 |
| - int nums2Left = 0; |
19 |
| - // 数组1右(大值)索引 |
20 |
| - int nums1Right = nums1.length - 1; |
21 |
| - // 数组2右(大值)索引 |
22 |
| - int nums2Right = nums2.length - 1; |
| 15 | + return (findKth(nums1, 0, nums2, 0, left) + findKth(nums1, 0, nums2, 0, right)) / 2.0; |
| 16 | + } |
| 17 | + |
| 18 | + private int findKth(int[] nums1, int i, int[] nums2, int j, int k) { |
| 19 | + if (i >= nums1.length) { |
| 20 | + return nums2[j + k - 1]; |
| 21 | + } |
| 22 | + if (j >= nums2.length) { |
| 23 | + return nums1[i + k - 1]; |
| 24 | + } |
| 25 | + if (k == 1) { |
| 26 | + return Math.min(nums1[i], nums2[j]); |
| 27 | + } |
| 28 | + int midVal1 = (i + k / 2 -1 < nums1.length) ? nums1[i + k / 2 - 1] : Integer.MAX_VALUE; |
| 29 | + int midVal2 = (j + k / 2 -1 < nums2.length) ? nums2[j + k / 2 - 1] : Integer.MAX_VALUE; |
23 | 30 |
|
24 |
| - // 从两边向中间,直到两个记录数相遇 |
25 |
| - while (true) { |
26 |
| - if (nums1Left > nums1Right) { |
27 |
| - if (nums2Left > nums2Right) { |
28 |
| - break; |
29 |
| - } |
30 |
| - leftNum = nums2[nums2Left++]; |
31 |
| - rightNum = nums2[nums2Right--]; |
32 |
| - } else if (nums2Left <= nums2Right){ |
33 |
| - leftNum = nums1[nums1Left] < nums2[nums2Left] ? nums1[nums1Left++] : nums2[nums2Left++]; |
34 |
| - rightNum = nums1[nums1Right] > nums2[nums2Right] ? nums1[nums1Right--] : nums2[nums2Right--]; |
35 |
| - } else { |
36 |
| - leftNum = nums1[nums1Left++]; |
37 |
| - rightNum = nums1[nums1Right--]; |
38 |
| - } |
| 31 | + if (midVal1 < midVal2) { |
| 32 | + return findKth(nums1, i + k / 2, nums2, j, k - k / 2); |
| 33 | + } else { |
| 34 | + return findKth(nums1, i, nums2, j + k / 2, k - k / 2); |
39 | 35 | }
|
40 |
| - return (leftNum + rightNum) * 1.0 / 2; |
41 | 36 | }
|
42 | 37 |
|
43 | 38 | }
|
0 commit comments