Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

 

Example 1:

Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:

Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Example 3:

Input: nums1 = [0,0], nums2 = [0,0]
Output: 0.00000
Example 4:

Input: nums1 = [], nums2 = [1]
Output: 1.00000
Example 5:

Input: nums1 = [2], nums2 = []
Output: 2.00000
 

Constraints:

nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106

这题直接暴力破解了。使用归并排序的思路,遍历到中间位置,记录下最后遍历的两个值。

假设是偶数,则取平均值,奇数直接返回最后一个值即可。


class MedianOfTwoSortedArrays : public Solution {
public:
    void Exec() {
        
    }
    double findMedianSortedArrays(const vector<int>& nums1, const vector<int>& nums2) {
        int p1 = 0, p2 = 0, count = 0, lv1 = 0, lv2 = 0;
        while (count <= (nums1.size() + nums2.size()) / 2) {
            ++count;
            if (p1 >= nums1.size()) {
                lv1 = lv2;
                lv2 = nums2[p2++];
            } else if (p2 >= nums2.size()) {
                lv1 = lv2;
                lv2 = nums1[p1++];
            } else {
                if (nums1[p1] <= nums2[p2]) {
                    lv1 = lv2;
                    lv2 = nums1[p1++];
                } else {
                    lv1 = lv2;
                    lv2 = nums2[p2++];
                }
            }
        }
        if ((nums1.size() + nums2.size()) % 2 != 0) {
            return lv2;
        }
        return float(lv1 + lv2) / 2;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day