-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4. Median of Two Sorted Arrays
41 lines (30 loc) · 1.7 KB
/
4. Median of Two Sorted Arrays
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
---------------------------------------------------qeustion--------------------------------------------------------
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
就是说给两个基本排好序,数组找到这两个数组的中间值。
--------------------------------------------------solution--------------------------------------------------------
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<int>nums;
std::merge(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), std::back_inserter(nums));
if(nums.size()%2 == 1){
return nums[(nums.size()+1)/2 -1];
}
return (nums[(nums.size()+1)/2]+nums[(nums.size()-1)/2])/2.0;
}
};
--------------------------------------------------analyse---------------------------------------------------------
解题思路:本办法,新建一个数组,然后将两个数组依次添加进这个数组。再使用vector的sort排序方法。我尝过过一次实现情况并不好
一是sort排序默认的一种排序方法虽然可以进行排序,但是对于两个已经排好序的数组,即组成数组基本已经排好序的情况下并不是最快的
方法。因此改用成归并排序,归并排序merge()的方法并不需要先组成一个数组,即在插入过程中就排序。最终从排好的数组中找到中间值
并返回。