LeetCode--4

来源:互联网 发布:ibm蓝云计算平台 编辑:程序博客网 时间:2024/06/03 19:42

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

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

Subscribe to see which companies asked this question.

解题思路

  1. 判断两个数组size的和为奇为偶;
  2. 合并两个数组;
  3. 冒泡排序;
  4. 根据1求出的奇偶输出中间数。
    方法简单,但效率低。

代码实现

class Solution {public:    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {        int m=nums1.size();        int n=nums2.size();        int flag=0;        if((m+n)%2==0) flag=1;//总个数为偶        vector<int> nums3;//整合为一个数组        for(int i=0; i<m; i++){            nums3.push_back(nums1[i]);        }        for(int i=0; i<n; i++){            nums3.push_back(nums2[i]);        }        for(int i=0; i<n+m-1; i++){//冒泡排序            int temp=nums3[i];            for(int j=n+m-1; j>i; j--){                if(temp>nums3[j]){                    nums3[i]=nums3[j];                    nums3[j]=temp;                    temp=nums3[i];                }            }        }        if(flag==1){//偶数            return double((nums3[(m+n)/2]+nums3[(m+n)/2-1])/2.0);        }        else{//奇数            return nums3[(m+n)/2];        }    }};
0 0