iT邦幫忙

2023 iThome 鐵人賽

DAY 21
0
自我挑戰組

leetcode題目分享系列 第 21

[Day 21] 4. Median of Two Sorted Arrays

  • 分享至 

  • xImage
  •  

使用binary search能讓時間複雜度在:O(log(min(m,n))),透過low & high管理上下限,找出mid

ref:https://leetcode.com/problems/median-of-two-sorted-arrays/solutions/4070371/94-96-binary-search-with-partitioning-o-log-min-m-n/?envType=daily-question&envId=2023-09-21

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        if(nums1.size() > nums2.size()){
            swap(nums1, nums2);
        }

        int m = nums1.size();
        int n = nums2.size();
        int low = 0, high = m;

        while(low <= high){
            int pX = (low + high) / 2;
            int pY = (m + n + 1) / 2 - pX;

            int maxX = (pX == 0) ? INT_MIN : nums1[pX - 1];
            int maxY = (pY == 0) ? INT_MIN : nums2[pY - 1];

            int minX = (pX == m) ? INT_MAX : nums1[pX];
            int minY = (pY == n) ? INT_MAX : nums2[pY];

            if(maxX <= minY && maxY <= minX){
                if((m + n) % 2 == 0){
                    return (max(maxX, maxY) + min(minX, minY)) / 2.0;
                } 
                else {
                    return max(maxX, maxY);
                }
            }
            else if(maxX > minY){
                high = pX - 1;
            }
            else{
                low = pX + 1;
            } 
        }
        return 0;
    }
};

上一篇
[Day 20] 1658. Minimum Operations to Reduce X to Zero
下一篇
[Day 22] 392. Is Subsequence
系列文
leetcode題目分享30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言