[LeetCode][Java] Median of Two Sorted Arrays

来源:互联网 发布:中电数据服务有限公司 编辑:程序博客网 时间:2024/05/22 14:09

题目:

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

题意:

合并两个有序数组,并返回新的数组的中位数。

算法分析:

若有n个数,n为奇数,则选择第(n+1)/2个为中位数,若n为偶数,则中位数是(n/2以及n/2+1)的平均数

代码如下:

public class Solution {    public double findMedianSortedArrays(int[] nums1, int[] nums2)     {    int[] list= new int[nums1.length+nums2.length];     double res=0;        for(int i=0;i<nums1.length;i++)        list[i]=nums1[i];        for(int i=nums1.length;i<nums1.length+nums2.length;i++)        list[i]=nums2[i-nums1.length];    Arrays.sort(list);    if((nums1.length+nums2.length)%2!=0)     res=list[(nums1.length+nums2.length)/2];    else     res=(double)(list[(nums1.length+nums2.length)/2]+list[(nums1.length+nums2.length)/2-1])/2;        return res;    }}


0 0
原创粉丝点击