[49] (Dichotomy) Find the median of two positively ordered arrays (LC 4)

Find the median of two positive arrays

Problem Description

Given two positive-order (from small to large) arrays nums1 and nums2 of size m and n, respectively. Please find and return the median of these two positive-order arrays.

Advanced: Can you design an algorithm with a time complexity of O(log (m+n)) to solve this problem?

Problem-solving ideas

Finding the median of an ordered array can be done directly in O(1) time: determine the length of the array, if it is an even number, take the average of the middle two numbers, if it is an odd number, take the middle value. Therefore, it is conceivable to merge the two arrays first and then find the median. Therefore, the test point of this question becomes how to merge two ordered arrays, using merge sorting, and the time complexity is O(m+n)

(Exhausted) The good problem solution written directly: detailed and popular thinking analysis, multiple solutions

In the problem solution, I saw the idea of ​​not merging the arrays: Knowing the length of the two arrays, then you can calculate the subscript of the median of the two arrays after sorting, and maintain two pointers, which initially point to the two array subscripts. At the position of 0, the pointer to the smaller value is moved back one bit each time (if a pointer has reached the end of the array, you only need to move the pointer of another array) until it reaches the position of the median. The time complexity of this method is also O(m+n).

If the time complexity is O(logm+n), the binary search method should be used, see the official solution .

Guess you like

Origin blog.csdn.net/qq_43424037/article/details/114678444