leetcode 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)).
You may assume nums1 and nums2 cannot be both empty.
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

// 我的解法: 耗时52ms,不算最优
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] array = new int[nums1.length + nums2.length];
        int p=0,q=0,index=0;
        while (p < nums1.length || q < nums2.length) {
            int pval = p < nums1.length ? nums1[p] : 0;
            int qval = q < nums2.length ? nums2[q] : 0;
            int tmp = -1;
            if ((q >= nums2.length || pval < qval) && (p < nums1.length)) { // 这里主要是想用一个while循环结束,但是这里的条件有些复杂,不是很利于判断
                tmp = pval;
                ++p;
            } else if ((p >= nums1.length || pval >= qval) && (q < nums2.length)) {
                tmp = qval;
                ++q;
            }
            array[index] = tmp;
            ++ index;
        }
        double res;
        res = array.length % 2 == 1 ? (double) array[array.length / 2] : (double) (array[array.length / 2 - 1] + array[array.length / 2]) / 2 * 1.0;
        return res;
    }
}

小结: 做这道题目的时候一开始想法是先排序再求值,思路没有问题,但是当写到一个while循环里时,中间的两个判断略显复杂。

这里突然想到好的实现的代码一定是不但方法巧妙,时间复杂度低,还有关键的一点就是可读性一定要好!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容