4. Median of Two Sorted Arrays (C++)

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) {
    vector<int> myvec(nums1.size()+nums2.size());
    int t=0,i,j;
    for(i=0;i<nums1.size();i++){
      myvec[t]=nums1[i];
      t++;
    }
    for(j=0;j<nums2.size();j++){
      myvec[t]=nums2[j];
      t++;
    }
    sort(myvec.begin(),myvec.end());
    i=t/2;
    if(t%2==0){
      j=i-1;
    }else{
      j=i;
    }
    return (myvec[i]+myvec[j])/2.0;
  }
};

posted @ 2017-02-28 18:09  DevinGu  阅读(130)  评论(0编辑  收藏  举报