1. 程式人生 > >LeetCode 4: Median of Two Sorted Arrays

LeetCode 4: Median of Two Sorted Arrays

over 排列 com assume 時間 pre des cti 中間

Description:

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

You may assume nums1 and nums2 cannot be both empty.

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

描述:

兩個有序數組nums1和nums2,數組元素數量分別為m和n。

尋找兩個數組的中位數。要求程序的時間復雜度為O(lg(m+n))。

假設數組nums1和nums2不同時為空。

示例1:

nums1 = [1, 3]

nums2 = [2]

中位數為2.0

示例2:

nums1 = [1, 2]

nums2 = [3, 4]

中位數為(2 + 3) / 2 = 2.5

方法:

首先,我們先理解中位數的概念和意義。中位數,又稱中點數,中值。中數是按順序排列的一組數據中居於中間位置的數,即在這組數據中,有一半的數據比他大,有一半的數據比他小。對於有限的數集,可以通過把所有觀察值高低排序後找出正中間的一個作為中位數。如果觀察值有偶數個,通常取最中間的兩個數值的平均數作為中位數。

LeetCode 4: Median of Two Sorted Arrays