LeetCode Median of Two Sorted Arrays

来源:互联网 发布:网络考试平台 编辑:程序博客网 时间:2024/06/07 06:57

一、题目

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)).

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

二、代码

简单合并,排序,取中值

class Solution {public:    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {         int *it;        int m = nums1.size()?nums1.size():0;        int n = nums2.size()?nums2.size():0;        int *merge = new int[m+n];        if(!nums1.empty()){            it = &*nums1.begin();            memcpy(merge,it,sizeof(int)*m);           }        if(!nums2.empty()){            it = &*nums2.begin();            memcpy(merge+m,it,sizeof(int)*n);          }        sort(merge,merge+m+n);        //注意数组下标和计算的下标区别        return (m+n)%2?1.0*merge[(m+n)>>1]:(merge[(m+n-1)>>1]+merge[(m+n)>>1])/2.0;    }};
原创粉丝点击