LeetCode-4:Median of Two Sorted Arrays

来源:互联网 发布:淘宝商品分享到微信 编辑:程序博客网 时间:2024/06/05 17:32

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

题意:给出两个排序好的数组, 求这两个数组的中位数. 时间复杂度要为O(log (m+n)).

感觉自己写的很水居然通过测试用例了惊讶,先记录下吧,以后有好的方法再过来更改吧

import java.util.ArrayList;import java.util.Collections;public class Solution {    public double findMedianSortedArrays(int[] nums1, int[] nums2) {        ArrayList<Double> list=new ArrayList<Double>();for(int i=0;i<nums1.length;i++){list.add((double)nums1[i]);}for(int i=0;i<nums2.length;i++){list.add((double)nums2[i]);}Collections.sort(list);if(list.size()%2==1){return list.get(list.size()/2);}else{return (list.get(list.size()/2-1)+list.get(list.size()/2))/2;}    }}


原创粉丝点击