leetcode4. Median of Two Sorted Arrays (find the median of two sorted arrays)

The main idea of ​​the title: Knowing two sorted arrays nums1 and nums2, the lengths are m and n respectively, the requirement is the median of all numbers after merging nums1 and nums2. The time complexity requires O(log(m+n))

Topic analysis: It is easy to think of the merge sort algorithm, which uses two pointers to point to nums1 and nums2, respectively, compares the size of the elements pointed to by the two pointers, whichever is smaller, moves back until both pointers point to the array end of . AC

Code display:

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        vector<int> result;
        vector<int>::iterator it1 = nums1.begin();
        vector<int>::iterator it2 = nums2.begin();
        while(it1!=nums1.end() || it2!=nums2.end()){
            if(it1==nums1.end()){
                result.insert(result.end(),it2,nums2.end());
                break;
            }
            if(it2==nums2.end()){
                result.insert(result.end(),it1,nums1.end());
                break;
            }
            if(*it1==*it2){
                result.push_back(*it1);
                result.push_back(*it2);
                it1++;
                it2++;
            }
            else if(*it1>*it2){
                result.push_back(*it2);
                it2++;
            }
            else{
                result.push_back(*it1);
                it1++;
            }
        }
        int len = result.size();
        if(len%2)
            return double(result[len/2]);
        else
            return double((result[len/2-1]+result[len/2])/2.0);
    }
};

Another more efficient way is to solve the median of two arrays nums1[middle1], nums2[middle2], and compare their sizes, there will be the following three relationships:

1.nums1[middle1]>nums2[middle2], then exclude the elements in nums1 after middle1, and exclude the elements in nums2 before middle2

2. nums1[middle1]=nums2[middle2], then return nums1[middle1] or nums2[middle2] as the final result

3. nums1[middle1]<nums2[middle2], then exclude the elements in nums1 before middle1, and exclude the elements in nums2 after middle2

This goes on recursively.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326038728&siteId=291194637