LeetCode 04 Finding the median (difficult) dichotomy of two positively ordered arrays

Title description:

A painstaking problem solution, like and follow the collection , one-click triplet, join us to check in together!

Title description:

Given two positive (from small to large) arrays nums1 and nums2 of size m and n.
Please find the median of these two positive arrays, and the time complexity of the algorithm is required to be O(log(m + n)).
You can assume that nums1 and nums2 will not be empty at the same time.

Example 1:

nums1 = [1, 3]
nums2 = [2]
then the median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]
then the median is (2 + 3)/2 = 2.5

Merging method (O(m+n))

Before the analysis, I really didn’t think of the O(log(m+n)) method for this question. I could only think of the O(m+n) merging. I didn’t expect how to use the dichotomy. Later, I read the solution of the problem. understand. But I understand it myself and share it with everyone.

This problem may not be difficult in itself, but it may be difficult in the time complexity of O(log(m+n)).

If you really can’t think of a good way, think about passing the level first, what method should you use?

Method one brute force method:
You can add two arrays to a total array, and then sort the array. The normal sorting is **O(nlogn)** time complexity. After sorting, take the median according to odd and even numbers.

Method two merging method:
The two arrays given are in order, and friends who are familiar with merging and sorting should be able to come up with this method, two in order. Just follow the process below to complete the merging:

  • The two arrays to be merged are respectively set with two pointers leftindex, rightindex all start from 0. The new array also sets the cursor index.

  • Compare the values ​​of the leftindex and rightindex positions of the two arrays, the smaller one is assigned to the new array and the new array cursor and the smaller cursor are both incremented by one.
    Insert picture description here

  • Repeat until one of the arrays is traversed, and the remaining value of the other array is added directly.
    Insert picture description here

Implementation code:

public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    
    
		 int a[]=new int[nums1.length+nums2.length];
		 int lindex=0,rindex=0;
		 int index=0;
		 while (lindex<nums1.length&&rindex<nums2.length) {
    
    
			if(nums1[lindex]<nums2[rindex])
			{
    
    
				a[index++]=nums1[lindex++];
			}
			else {
    
    
				a[index++]=nums2[rindex++];
			}
		}
		 while (lindex<nums1.length) {
    
    
				a[index++]=nums1[lindex++];
		}
		 while (rindex<nums2.length) {
    
    
				a[index++]=nums2[rindex++];
		}
		 if(a.length%2==0)
			 return (double)(a[a.length/2-1]+a[a.length/2])/2;
		 else {
    
    
			return a[a.length/2];
		}
		 
	 }

Dichotomy (O(log(m+n)))

Thinking of orderly, it is O(log(m+n)) time complexity. It is estimated that most people can think of dichotomy. I was the same at the time, but what should I think about this is a problem. Record my wrong thoughts:

Two points, two points to find two in the middle. Then there is a long one, and one short. According to the comparison of the two values, it is estimated which interval the median should be in... and then the brain is powered off.

A simple analysis of the median :

  • If the sum of the lengths of the two arrays is odd, then the final median is determined by one digit .
  • If the sum of the lengths of the two arrays is even, then the final median is determined by averaging the two digits .

Simple analysis of two arrays :

  • One of the two arrays should be a bit longer and the other a bit longer (the same length does not affect).
  • The median may divide both arrays into two parts: one is less than the median, and the other is greater than the median. But the total number of the two parts should be the same .
    Insert picture description here

Analysis of the two arrays and the median position :

  • We know that although the two arrays may have the same length (does not affect), the normal situation should be one long (m) and one short (n) . What is the relationship between the coordinates m1 and n1 corresponding to the long and short arrays and the median coordinates?
  • No matter the sum is odd or even, it satisfies (m1+n1)=(m+n)/2; because the two arrays are in order, the total is less than half of the median. Where m and n are fixed values. That is, no matter how you change, the two coordinate numbers are the sum of the fixed value !

How to analyze the fixed value coordinates

  • Since the sum of the two coordinates is a fixed value, can one of them be regarded as an independent variable and the other as an independent variable? For example, if x+y=5 is not easy to analyze but y=5-x, you can analyze x and y at the same time. Right?
  • Then choose the long one as the variable or the short one as the variable? The short one, why, mainly because if we regard the long one as a variable, we cannot correspond to the short one in some areas (because even if the length is added to the short one, it will not reach half, which is troublesome to deal with) :
    Insert picture description here
  • But the short one can avoid this situation well:
    Insert picture description here

So we use dichotomy to find the small interval and find the final result. You may ask: What kind of situation can be satisfied to determine the vicinity of this line to produce the median ?

  • When searching for numbers in binary, the left side is smaller than the right side of the line. In this case, the binary search is a balanced result.
    Insert picture description here

Finally found the index line. What you should pay attention to when comparing values :

  • When taking the left side, if the index on the left side is 0, when taking the right side, the index is the maximum value:
    Insert picture description here
  • So when you finally take the value, you need to consider whether there are values ​​on the left and right sides. At the same time, the one that takes the length should be compared, because there may be equal length situations such as:, 1 2 3 4and 5 6 7 8this goes to the limit. Need to judge, of course, the realization process is simplified with trinocular operation!

In general:

  • According to the short binary search position , first find the line index, indicating that the median is generated nearby. (Odd and even numbers are looking for because you can divide by 2 can be a general expression)
  • If the total number is odd , then it is the largest one on the left side of the line (two comparisons or only one)
  • If the total number is even , then the value of the largest one on the left side of the line (two comparisons or only one) and the smallest one on the right side of the line (two comparisons or only one) are averaged. Note that it is of double type .
  • Other points to note, figure out the index starts from 0, figure out the difference between the logical number and the number used in the array display .

Attach the code:

public static double findMedianSortedArrays2(int[] nums1, int[] nums2) {
    
    
	if(nums1.length>nums2.length)//保证num1长度小,如果不小我交换一下
	{
    
    
		int team[]=nums2.clone();
		nums2=nums1;
		nums1=team;
	}	
	 int k=(nums1.length+nums2.length+1)/2;//理论中位数满足的位置
	 int left=0,right=nums1.length;//二分查找短的
	 
	 while (left<right) {
    
    //找到对应位置
		int m1=(left+right)/2;//在短的位置
		int m2=k-m1;//在长的第几个
		//System.out.println(m1+" "+m2);
		if(nums1[m1]<nums2[m2-1])//left右移
			left=m1+1;
		else {
    
    //right左移
			right=m1;
		}
	}
	//System.out.println(left+" "+k);
	//左侧最大和右侧最小那个先算出来再说,根据奇偶再使用
	double leftbig= Math.max(left==0?Integer.MIN_VALUE:nums1[left-1], k-left==0?Integer.MIN_VALUE:nums2[k-left-1]);
	double rightsmall=Math.min(left==nums1.length?Integer.MAX_VALUE:nums1[left],k-left==nums2.length?Integer.MAX_VALUE:nums2[k-left]);
	//System.out.println(rightsmall);
	if((nums1.length+nums2.length)%2==0)
	{
    
    
		return (leftbig+rightsmall)/2;
	}
	else {
    
    
		return leftbig;
	}		
 }

Conclusion

After this punch-in is over, we will continue to work hard.

As for other methods, I won't learn it for the time being, I feel that this question is still quite difficult, and it is necessary to understand the main points.

I heard that handsome people prefer to give people likes and collections. Where are the likes and collections enough? Follow the bigsaiofficial account :, reply to the group, let's check in together. At present, more than 100 csdn friends have joined to check in.

Guess you like

Origin blog.csdn.net/qq_40693171/article/details/107896810