1 有序数组合并
代码语言:javascript复制class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<int> merge;
int size1 = nums1.size();
int size2 = nums2.size();
int sizem = size1 size2;
int l1 = 0, l2 = 0;
// 1.合并2个有序数组,合并完即为有序,O(n)复杂度
while (l1 < size1 || l2 < size2) {
if (l1 == size1) merge.emplace_back(nums2[l2 ]);
else if (l2 == size2) merge.emplace_back(nums1[l1 ]);
else if (nums1[l1] < nums2[l2])
merge.emplace_back(nums1[l1 ]);
else if (nums1[l1] >= nums2[l2])
merge.emplace_back(nums2[l2 ]);
}
// 2.偶数个,则取两个的一半;奇数个则直接取中间索引对应值
if (sizem % 2 == 0)
return merge[sizem / 2 - 1] (merge[sizem / 2] - merge[sizem / 2 - 1]) * 1.0 / 2;
return merge[sizem / 2];
}
};