There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Subscribe to see which companies asked this question
1 class Solution { 2 public: 3 /* 4 * 首先的想法是用额外的一个vector保存排好序的数组,快速排序 o(nlogn) 5 * 6 */ 7 double _findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { 8 vector<int>::iterator it; 9 vector<int> all_nums; 10 11 for (it=nums1.begin(); it!=nums1.end(); it++) { 12 all_nums.push_back(*it); 13 } 14 15 for (it=nums2.begin(); it!=nums2.end(); it++) { 16 all_nums.push_back(*it); 17 } 18 19 sort(all_nums.begin(), all_nums.end()); 20 21 int len_all_nums = all_nums.size(); 22 if (len_all_nums % 2 == 1) { 23 return all_nums[len_all_nums / 2]; 24 } else { 25 double mid_left = all_nums[len_all_nums / 2 - 1]; 26 double mid_right = all_nums[len_all_nums / 2]; 27 double mid_num = (mid_left + mid_right) / 2; 28 return mid_num; 29 } 30 } 31 /* 32 * 也可以转换为找到两个排序链表的第i个数, 不过太麻烦了 33 * 1. 34 * */ 35 double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { 36 int all_len = nums1.size() + nums2.size(); 37 int first_index = -1; 38 int second_index = -1; 39 if (all_len % 2 == 1) { 40 first_index = all_len / 2; 41 } else { 42 first_index = all_len / 2 - 1; 43 second_index = all_len / 2; 44 } 45 double first_num = 0; 46 double second_num = 0; 47 //下面就是找到对应的数 48 int n1 = 0; 49 int n2 = 0; 50 int find_index = 0; 51 for (;find_index<first_index; find_index++) { 52 if ((n1 < nums1.size()) && (n2< nums2.size())) { 53 if (nums1[n1] <= nums2[n2]) { 54 n1++; 55 } else { 56 n2++; 57 } 58 } else if(n1 < nums1.size()) { 59 n1++; 60 } else { 61 n2++; 62 } 63 } 64 65 if (n1 == nums1.size()) { 66 first_num = nums2[n2]; 67 if (second_index != -1) { 68 second_num = nums2[n2 + 1]; 69 } 70 } else if (n2 == nums2.size()) { 71 first_num = nums1[n1]; 72 if (second_index != -1) { 73 second_num = nums1[n1 + 1]; 74 } 75 } else { 76 /* 77 first_num = min(nums1[n1], nums2[n2]); 78 //second_num = max(nums1[n1], nums2[n2]); 79 if ((n1 + 1) < nums1.size()) { 80 second_num = min(nums1[n1 + 1], nums2[n2]); 81 } else { 82 second_num = nums2[n2]; 83 } 84 */ 85 if (nums1[n1] <= nums2[n2]) { 86 first_num = nums1[n1]; 87 if ((n1 + 1) < nums1.size()) { 88 second_num = min(nums1[n1 + 1], nums2[n2]); 89 } else { 90 second_num = nums2[n2]; 91 } 92 } else { 93 first_num = nums2[n2]; 94 if ((n2 + 1) < nums2.size()) { 95 second_num = min(nums1[n1], nums2[n2 + 1]); 96 } else { 97 second_num = nums1[n1]; 98 } 99 } 100 } 101 102 if (second_index != -1) { 103 return (first_num + second_num) / 2.0; 104 } else { 105 return first_num; 106 } 107 } 108 };
原文:http://www.cnblogs.com/SpeakSoftlyLove/p/5095202.html