码迷,mamicode.com
首页 > 其他好文 > 详细

LeeCode(No4 - Median of Two Sorted Arrays)

时间:2018-01-05 19:52:37      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:find   leecode   int   https   strong   get   dex   com   思路   

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

刚看到题基本思路是将两个数据按顺序排列然后取中位数(偶数取中位两数平均数)

下面是自己的方法(姑且称之为齿轮法,也是比较传统的方法):

public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    ArrayList<Integer> arrayList = new ArrayList<>();
    int index1 = 0;
    int index2 = 0;
    for (int i =0; i< nums1.length; i++) {
        for (int j = index2; j < nums2.length; j++) {
            if (nums1[index1] <= nums2[j]) {
                arrayList.add(nums1[index1]);
                index1 ++;
                break;
            } else {
                arrayList.add(nums2[j]);
                index2 ++;
            }
        }
    }

    if(index1 < nums1.length) {
        for(; index1 < nums1.length; index1++){
            arrayList.add(nums1[index1]);
        }
    }

    if(index2 < nums2.length) {
        for(; index2 < nums2.length; index2++){
            arrayList.add(nums2[index2]);
        }
    }

    int totalSize = arrayList.size();
    if(totalSize % 2 == 0) {
        return (arrayList.get(totalSize / 2 - 1) + arrayList.get(totalSize / 2)) / 2.0;
    } else {
        return arrayList.get(totalSize / 2);
    }
}

果不其然,性能只打败了13.8%的人。

这个题目的难度是Hard,考虑了许久没有更好解决方案,所以查看官网,果然演变为数学问题,感兴趣的可以看下下面地址

 

参考:

https://leetcode.com/problems/median-of-two-sorted-arrays/

LeeCode(No4 - Median of Two Sorted Arrays)

标签:find   leecode   int   https   strong   get   dex   com   思路   

原文地址:https://www.cnblogs.com/roostinghawk/p/8206155.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!