leetcode 刷题日记——Median of Two Sorted Arrays

来源:互联网 发布:网络工具书 编辑:程序博客网 时间:2024/06/07 19:39

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(int[] nums1, int[] nums2) {        int m=nums1.length;        int n=nums2.length;        int[] com =new int[m+n];         int k=0,i=0,j=0;        while( i<m || j<n){            while(i<m&&j<n){            if(nums1[i]<=nums2[j]) com[k++]=nums1[i++];            else com[k++]=nums2[j++];            }            while(i<m) com[k++]=nums1[i++];            while(j<n) com[k++]=nums2[j++];        }        if((m+n)%2==0)          return (double)0.5*(com[(m+n)/2-1]+com[(m+n)/2]);        else          return  (double)com[(m+n)/2];        }}

 
原创粉丝点击