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
思路:先判斷兩數組是否爲空,對兩個數組設置比較下標left、right,循環比較兩下標對應的數組值,將小者放入新的數組res中,移動下標。當一個數組下標到末尾時將另一個數組中未進行對比的所有元素直接拷貝進新的數組。最後找到兩數組的中數就比較簡單了。注意這種方法的時間複雜度爲O(m+n),
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int left = 0;
int right = 0;
vector<int> res;
int n = nums1.size() + nums2.size();
if(nums1.empty() && !nums2.empty())
if(n%2 == 0)
return (nums2[n/2 - 1] + nums2[n/2]) / 2.0;
else
return float(nums2[n/2]);
if(!nums1.empty() && nums2.empty())
if(n%2 == 0)
return (nums1[n/2 - 1] + nums1[n/2]) / 2.0;
else
return float(nums1[n/2]);
while(left < (int)(nums1.size()) && right < (int)(nums2.size())){
if(nums1[left] < nums2[right]){
res.push_back(nums1[left]);
left = left + 1 ;
}
else{
res.push_back(nums2[right]);
right = right + 1;
}
}
for(int i=left;i<(int)nums1.size();i++){
res.push_back(nums1[i]);
}
for(int i=right;i<(int)nums2.size();i++){
res.push_back(nums2[i]);
}
if(n % 2 == 0)
return (res[n/2 - 1] + res[n/2]) / 2.0;
else
return float(res[n/2]);
}
};
優化:當然,可以先計算中間元素所在的位置,直接比較兩數組中元素值(不用另外的新數組),當while循環到中間位置時,輸出該元素值(或通過計算當前元素與前一個元素和的平均值(總元素個數爲偶數時)),這樣同時降低了算法的時間和空間複雜度。
bool oddLength = ((int)(nums1.size() + nums2.size()) % 2) != 0;
int medianLocation = ((int)(nums1.size() + nums2.size()) / 2) + 1;
int i=0;
int j=0;
int indexCount=0;
int current =0;
int prev= 0;
while(i!=(int)nums1.size() || j!=(int)nums2.size()) {
prev = current;
if(i!=(int)nums1.size() && j!=(int)nums2.size()) {
current = min(nums1[i],nums2[j]);
if(current == nums1[i])
i++;
else
j++;
} else {
if(i==(int)nums1.size())
current = nums2[j++];
else
current = nums1[i++];
}
indexCount++;
if(indexCount==medianLocation)
return oddLength? current : ((double)(current+prev))/2;
}
return 0;