leetcode-個人題解4
阿新 • • 發佈:2019-02-03
LEETCODE專題
4. Median of Two Sorted Arrays
首先先上個題目要求:
這個題目要求要仔細看,我之前就是因為沒仔細看導致審錯了題,3次。。。
題目大意就是說:給定兩個有序陣列,找出它們有序拼接之後的中位數。
之前審錯題的分析就免了吧,現在我們直接來考慮正確的做法和問題。
- 問題
- 如何把兩個陣列有序地拼接在一起
- 如何在有序陣列中尋找中位數
對於第二個問題,我想就算是程式設計入門的朋友也不會花太多時間,就留給讀者自己解決吧。我們著重來探討下如何解決第一個問題。
思路也很簡單,其實就是設定兩個陣列的遊標,然後比較遊標對應的陣列元素,取小的元素並且將相應的遊標+1。這樣一趟過後就可以實現有序拼接了。而因為中位數並不需要我們把最終陣列的中位數之後的元素也給加進去,所以筆者的迴圈做到中位數那裡就停止了。最後按照中位數的求法直接求出中位數就可以了。
程式碼如下:
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
/* The total_array is to store all the two array,
* which ends at the (nums1.size() + nums2.size() / 2),
* because that's enough to compute the median
*/
int total_array[nums1.size() + nums2.size()];
for (int i = 0, j = 0; i <= nums1.size() || j <= nums2.size(); ) {
/* The IF ELSE block is to judge whose size is zero,
* or if the index is at the end, or to compare the
* corresponding number. Then, we put
* the proper number in the total_array
*/
if (nums1.size() == 0 || i == nums1.size()
|| (nums2.size() > 0 && j < nums2.size() && nums1[i] > nums2[j]) ) {
total_array[i + j] = nums2[j];
j++;
} else if (nums2.size() == 0 || j == nums2.size() || nums1[i] <= nums2[j]) {
total_array[i + j] = nums1[i];
i++;
}
if (i + j - 1>= (nums1.size() + nums2.size() ) / 2) break;
}
double median = ( (double)total_array[(nums1.size() + nums2.size() ) / 2] +
(double)total_array[(nums1.size() + nums2.size() - 1 ) / 2] ) / 2;
return median;
}
};
時間複雜度:O(m + n)
空間複雜度:O(m + n)