1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
#include <iostream> #include <vector>
using namespace std;
class Solution { public: double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2) { int m = nums1.size(); int n = nums2.size(); if ((m + n) % 2 == 1) { return findKthSortedArrays(nums1, nums2, (m + n + 1) / 2); } else { int left = findKthSortedArrays(nums1, nums2, (m + n) / 2); int right = findKthSortedArrays(nums1, nums2, (m + n) / 2 + 1); return (left + right) / 2.0; } }
private: int findKthSortedArrays(vector<int> &nums1, vector<int> &nums2, int k) { int m = nums1.size(); int n = nums2.size(); int index1 = 0; int index2 = 0;
while (true) { if (index1 == m) { return nums2[index2 + k - 1]; } if (index2 == n) { return nums1[index1 + k - 1]; } if (k == 1) { return min(nums1[index1], nums2[index2]); }
int newIndex1 = min(index1 + k / 2 - 1, m - 1); int newIndex2 = min(index2 + k / 2 - 1, n - 1); if (nums1[newIndex1] < nums2[newIndex2]) { k = k - (newIndex1 - index1 + 1); index1 = newIndex1 + 1; } else if (nums1[newIndex1] > nums2[newIndex2]) { k = k - (newIndex2 - index2 + 1); index2 = newIndex2 + 1; } else { k = k - (newIndex1 - index1 + 1); index1 = newIndex1 + 1; } }
return -1; } };
int main(int argc, char const *argv[]) { Solution solu; vector<int> nums1{1, 3}; vector<int> nums2{2}; double res = solu.findMedianSortedArrays(nums1, nums2); cout << res << endl;
nums1 = vector<int>{1, 2}; nums2 = vector<int>{3, 4}; res = solu.findMedianSortedArrays(nums1, nums2); cout << res << endl; return 0; }
|