leetcode4 median Of two sorted array

Posted 玛吉

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode4 median Of two sorted array相关的知识,希望对你有一定的参考价值。

 

leetcode4

此题归在二分法中:

大概思想:将两个数组分别分为两个部分,两者的数值较小的数字,就是合并后数组的前半部分

难点在:找到第一个数组的位置i,则第二数组的位置j = (m+n +1)/2 - i;

此后,由i,j找到中位数,如果m+n为奇数,则max_left即为所求,否则:(max_left + min_right)/2为结果

 

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        
        int m = nums1.size();
        int n = nums2.size();
        if(m > n)return findMedianSortedArrays(nums2,nums1);
        
        int left = 0;
        int right = m;
        int i = -1;
        int j = -1;
        while(true){
        	i = (left + right) / 2;
        	j = (m + n + 1) / 2 - i;
        	
        	if((i == 0 || j == n || nums1[i-1] <= nums2[j]) && (j == 0 || i == m || nums2[j-1] <= nums1[i])){
        		break;
			}else if(i > 0 && nums1[i-1] > nums2[j]){
				right = i - 1;
			}else if(j > 0 && nums2[j-1] > nums1[i]){
				left = i + 1;
			}
		}
		
		//find the median num
		int max_left = -1;
		int min_right = -1;
		
		if(i == 0){
			max_left = nums2[j-1];
		}else if(j == 0){
			max_left = nums1[i-1];
		}else{
			max_left = max(nums2[j-1] , nums1[i-1]);
		}
		
		if((m+n) % 2){
			return max_left;	
		}
		
		
		if(i == m){
			min_right = nums2[j];
		}else if(j == n){
			min_right = nums1[i];
		}else{
			min_right = min(nums2[j] , nums1[i]);
		};
		
		
		return  double(max_left + min_right) / 2;//保证中位数的准确性
		
    }
};

  

以上是关于leetcode4 median Of two sorted array的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode4. Median of Two Sorted Arrays

19.1.19 [LeetCode4]Median of Two Sorted Arrays

leetcode4 median Of two sorted array

LeetCode4. Median of Two Sorted Arrays---vector实现O(log(m+n)--- findkth

算法Median of Two Sorted Arrays

算法Median of Two Sorted Arrays