其他分享
首页 > 其他分享> > LeetCode Top100【困难】

LeetCode Top100【困难】

作者:互联网

目录

目录

困难

4. 寻找两个正序数组的中位数

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
//归并排序部分算法,主要是看是奇偶
            int l1 = nums1.length;
            int l2 = nums2.length;
            int c1 = 0;
            int c2 = 0;
            int left = (l1 + l2 - 1) / 2;
            int right = (l1 + l2) / 2;
            int rst1 = 0;
            int rst2 = 0;
            boolean finish = false;
            //只要有一个达到末尾就退出
            while (c1 < l1 && c2 < l2) {
                if (nums1[c1] <= nums2[c2]) {
                    rst2 = nums1[c1];
                    if (c1 + c2 == right) {
                        finish = true;
                        break;
                    }
                    rst1 = nums1[c1];
                    c1++;
                } else {
                    rst2 = nums2[c2];
                    if (c1 + c2 == right) {
                        finish = true;
                        break;
                    }
                    rst1 = nums2[c2];
                    c2++;
                }
            }

            if (!finish) {
                if (c1 < l1) {
                    while (c1 < l1) {
                        rst2 = nums1[c1];
                        if (c1 + c2 == right) {
                            break;
                        }
                        rst1 = nums1[c1];
                        c1++;
                    }
                } else {
                    while (c2 < l2) {
                        rst2 = nums2[c2];
                        if (c1 + c2 == right) {
                            break;
                        }
                        rst1 = nums2[c2];
                        c2++;
                    }
                }
            }
            if (left == right) {
                return rst2;
            } else {
                return (rst1 + rst2) / 2;
            }
        }
    }

TOP


标签:int,困难,nums1,l2,数组,l1,c1,Top100,LeetCode
来源: https://www.cnblogs.com/wftop1/p/16394341.html