Description
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)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
AC代碼
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int i=0, j=0; // 這兩個變量用於作爲index指示在數組中的位置
int x=0, y=0; // x, y用於指示兩個數組中遍歷到的的當前值
int pre_val=0, cur_val=0; // 這兩個變量用於指示當前值和前一個值
int count=1; // count用於指示當前總共遍歷的數的個數
int sum_size = nums1.size() + nums2.size();
int target = sum_size/2 + 1;
bool even = (sum_size%2 == 1) ? true:false;
while(1) {
// 有可能存在數組越界的情況,因此這裏給越界的情況加一個臨時值,便於後面的判斷
if(i<nums1.size()) {
x = nums1[i];
} else {
x = INT_MAX - 1;
}
if(j<nums2.size()) {
y = nums2[j];
} else {
y = INT_MAX - 1;
}
// 如果數組中的值超過了INT_MAX, 直接返回0
if(x >= INT_MAX || y >= INT_MAX) return 0;
// 取當前最小的值作爲cul_val,相當於是一個排序
if(x < y) {
cur_val = x;
++i;
} else {
cur_val = y;
++j;
}
// count == target 說明已經到了中位數的位置,接下來要來判定奇偶性
if(count == target) {
if(even) {
return cur_val;
} else {
return double((cur_val + pre_val)/2.0);
}
}
// 設置pre_val的初衷就是解決偶數的情況
pre_val = cur_val;
++count;
}
}
};
測試代碼
int main() {
Solution s;
vector<int> nums1{1, 3};
vector<int> nums2{2};
cout << "Median of nums1 and nums2 is " << s.findMedianSortedArrays(nums1, nums2)<<endl;
vector<int> nums3{1, 2};
vector<int> nums4{3, 4};
cout << "Median of nums3 and nums4 is " << s.findMedianSortedArrays(nums3, nums4)<<endl;
}
總結
這題的難度屬於Hard,上述的解法的核心思想是同時遍歷兩個數組,根據當前的最小值決定遍歷的走向。註釋比較詳細。