二分查找——寻找两个正序数组的中位数

 力扣

   //此题的关键是快速删除,让指针快速移动;

    //可以使用二分查找,加入要找第k项,那就在两个数组里都找到k/2项,如果nums1[k/2]<nums2[k/2]那么nums1的k/2项以前的肯定都不满足;舍去;

    //这样我们就找的是抛弃后的nums1和为抛弃的nums2的k-k/2项;那么我们在找各自的(k-k/2)/2项,再舍去小的数组;

    //假如一个数组已经抛弃结束了,我们只用返回另一数组的指定项就行了;

    //如果两个相等,那么我们返回就行了;

    //除此以外还要考虑偶数项奇数项的问题;

class Solution {

public:

    int getKthElement(const vector<int>& nums1, const vector<int>& nums2, int k) {

        /* 主要思路:要找到第 k (k>1) 小的元素,那么就取 pivot1 = nums1[k/2-1] 和 pivot2 = nums2[k/2-1] 进行比较

         * 这里的 "/" 表示整除

         * nums1 中小于等于 pivot1 的元素有 nums1[0 .. k/2-2] 共计 k/2-1 个

         * nums2 中小于等于 pivot2 的元素有 nums2[0 .. k/2-2] 共计 k/2-1 个

         * 取 pivot = min(pivot1, pivot2),两个数组中小于等于 pivot 的元素共计不会超过 (k/2-1) + (k/2-1) <= k-2 个

         * 这样 pivot 本身最大也只能是第 k-1 小的元素

         * 如果 pivot = pivot1,那么 nums1[0 .. k/2-1] 都不可能是第 k 小的元素。把这些元素全部 "删除",剩下的作为新的 nums1 数组

         * 如果 pivot = pivot2,那么 nums2[0 .. k/2-1] 都不可能是第 k 小的元素。把这些元素全部 "删除",剩下的作为新的 nums2 数组

         * 由于我们 "删除" 了一些元素(这些元素都比第 k 小的元素要小),因此需要修改 k 的值,减去删除的数的个数

         */



        int m = nums1.size();

        int n = nums2.size();

        int index1 = 0, index2 = 0;



        while (true) {

            // 边界情况

            if (index1 == m) {

                return nums2[index2 + k - 1];

            }

            if (index2 == n) {

                return nums1[index1 + k - 1];

            }

            if (k == 1) {

                return min(nums1[index1], nums2[index2]);

            }



            // 正常情况

            int newIndex1 = min(index1 + k / 2 - 1, m - 1);

            int newIndex2 = min(index2 + k / 2 - 1, n - 1);

            int pivot1 = nums1[newIndex1];

            int pivot2 = nums2[newIndex2];

            if (pivot1 <= pivot2) {

                k -= newIndex1 - index1 + 1;

                index1 = newIndex1 + 1;

            }

            else {

                k -= newIndex2 - index2 + 1;

                index2 = newIndex2 + 1;

            }

        }

    }



    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {

        int totalLength = nums1.size() + nums2.size();

        if (totalLength % 2 == 1) {

            return getKthElement(nums1, nums2, (totalLength + 1) / 2);

        }

        else {

            return (getKthElement(nums1, nums2, totalLength / 2) + getKthElement(nums1, nums2, totalLength / 2 + 1)) / 2.0;

        }

    }

};




 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值