|
1 | 1 | #include <stdio.h>
|
2 | 2 | #include <stdlib.h>
|
3 | 3 |
|
4 |
| -static double find_kth(int a[], int alen, int b[], int blen, int k) |
5 |
| -{ |
6 |
| - /* Always assume that alen is equal or smaller than blen */ |
7 |
| - if (alen > blen) { |
8 |
| - return find_kth(b, blen, a, alen, k); |
9 |
| - } |
10 |
| - |
11 |
| - if (alen == 0) { |
12 |
| - return b[k - 1]; |
13 |
| - } |
14 |
| - |
15 |
| - if (k == 1) { |
16 |
| - return a[0] < b[0] ? a[0] : b[0]; |
17 |
| - } |
18 |
| - |
19 |
| - /* Divide k into two parts */ |
20 |
| - int ia = k / 2 < alen ? k / 2 : alen; |
21 |
| - int ib = k - ia; |
22 |
| - if (a[ia - 1] < b[ib - 1]) { |
23 |
| - /* a[ia - 1] must be ahead of k-th */ |
24 |
| - return find_kth(a + ia, alen - ia, b, blen, k - ia); |
25 |
| - } else if (a[ia - 1] > b[ib - 1]) { |
26 |
| - /* b[ib - 1] must be ahead of k-th */ |
27 |
| - return find_kth(a, alen, b + ib, blen - ib, k - ib); |
28 |
| - } else { |
29 |
| - return a[ia - 1]; |
30 |
| - } |
31 |
| -} |
32 |
| - |
33 | 4 | static double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size)
|
34 | 5 | {
|
35 |
| - int half = (nums1Size + nums2Size) / 2; |
36 |
| - if ((nums1Size + nums2Size) & 0x1) { |
37 |
| - return find_kth(nums1, nums1Size, nums2, nums2Size, half + 1); |
| 6 | + int sum = nums1Size + nums2Size; |
| 7 | + int *nums = malloc(sizeof(int) * sum); |
| 8 | + int i = 0, j = 0, k = 0; |
| 9 | + int half = sum / 2 + 1; |
| 10 | + while (k < half) { |
| 11 | + int n; |
| 12 | + if (i < nums1Size && j < nums2Size) { |
| 13 | + n = (nums1[i] < nums2[j]) ? nums1[i++] : nums2[j++]; |
| 14 | + } else if (i < nums1Size) { |
| 15 | + n = nums1[i++]; |
| 16 | + } else if (j < nums2Size) { |
| 17 | + n = nums2[j++]; |
| 18 | + } |
| 19 | + nums[k++] = n; |
| 20 | + } |
| 21 | + if (sum % 2) { |
| 22 | + return nums[k-1]; |
38 | 23 | } else {
|
39 |
| - return (find_kth(nums1, nums1Size, nums2, nums2Size, half) + find_kth(nums1, nums1Size, nums2, nums2Size, half + 1)) / 2; |
| 24 | + return (nums[k-1] + nums[k-2]) / 2.0; |
40 | 25 | }
|
41 | 26 | }
|
42 | 27 |
|
|
0 commit comments