leetcode 4.Median of Two Sorted Arrays

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

c++ 思路:因为题目要求算法复杂度达到O(m+n),所以,我们仅可以进行便利一次数组。我的做法是,用一个vector进行保存顺序存储的序列。之后判断大小是偶数么?偶数返回下标为中间两个数的和。是奇数么?奇数返回中间一个数。 好的代码除了追求短小精悍之外,依旧需要一定的可读性。

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        vector<int> merge;
        int i=0,j=0;
        while(true){
            if(i<nums1.size()&&j<nums2.size())//i,j都有效
                if(nums1[i]<nums2[j]) merge.push_back(nums1[i++]);
                else merge.push_back(nums2[j++]);
            if(i>=nums1.size())
                while(j<nums2.size()) merge.push_back(nums2[j++]);
            if(j>=nums2.size())
                while(i<nums1.size()) merge.push_back(nums1[i++]);
            if(i>=nums1.size()&&j>=nums2.size()) break;
        }
        if(merge.size()%2==0) 
            return (merge[merge.size()/2]*1.0+merge[merge.size()/2-1]*1.0)/2.0;
        else return merge[merge.size()/2]*1.0;
    }
};
posted @ 2019-12-30 03:18  SteveYu  阅读(157)  评论(0编辑  收藏  举报