【LeetCode解答四】Median of Two Sorted Arrays问题Java解答

来源:互联网 发布:视频播放插件video.js 编辑:程序博客网 时间:2024/06/03 16:20

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)),其实我自己写的时候只是考虑最简单的算法,没有算时间复杂度…所以我的答案的时间复杂度是多少我也不知道。
我的做法就是将两个数组按照从小到大的顺序合并成一个数组,再求数组中间值就简单了,但是代码的冗长我自己都难以直视,一会儿看看别的大牛的博客看看能不能做一些优化,运行时间应该还算过得去。

double result = 0.0;        //定义最终数组长度        int sum = nums1.length + nums2.length;        int[] nums3 = new int[sum];        //若其中一数组为空,则最终数组直接等于另一个数组        if(nums1.length == 0){            nums3 = nums2;        }        if (nums2.length == 0){            nums3 = nums1;        }        int i = 0;        int j = 0;        //以flag作为标识符        int flag1;        int flag2;        //循环条件:两数组均不为空且任一指针不到数组尽头        while ((nums1.length!=0 && nums2.length != 0) && (i < nums1.length || j < nums2.length)){            //若指针到数组尽头 为防止IndexOutOfBoundsException,对标识符做减一处理            if (i >= nums1.length){                flag1 = i-1;            } else{                flag1 = i;            }            if (j >= nums2.length){                flag2 = j-1;            } else{                flag2 = j;            }            //若任一指针没有到数组尽头,则向最终数组中填入数字            if (!(i + j == sum)){                nums3[i+j] = Math.min(nums1[flag1],nums2[flag2]);            }            //若数组一的数字比较小            if (nums1[flag1] < nums2[flag2]){                if(i < nums1.length - 1){                    i ++;                } else{                    //若数组1到了尽头,则使数组1的最大值比数组2大                    nums1[nums1.length - 1] = nums2[nums2.length - 1] + 1;                    i ++;                }            } else{                if(j < nums2.length - 1){                    j ++;                } else{                    nums2[nums2.length - 1] = nums1[nums1.length - 1] + 1;                    j ++;                }            }        }//        System.out.println(Arrays.toString(nums3));        int num = sum / 2;        if (nums3.length % 2 ==0){            double num1 = nums3[num - 1];            double num2 = nums3[num];            result = (num1 + num2) / 2;        } else{            result = nums3[num];        }        return result;