-
Notifications
You must be signed in to change notification settings - Fork 0
/
4.寻找两个正序数组的中位数.cpp
118 lines (112 loc) · 2.4 KB
/
4.寻找两个正序数组的中位数.cpp
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/*
* @Author: your name
* @Date: 2021-04-27 23:36:14
* @LastEditTime: 2021-04-28 00:44:37
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \project\Leetcode\4.寻找两个正序数组的中位数.cpp
*/
/*
* @lc app=leetcode.cn id=4 lang=cpp
*
* [4] 寻找两个正序数组的中位数
*
* https://leetcode-cn.com/problems/median-of-two-sorted-arrays/description/
*
* algorithms
* Hard (40.02%)
* Likes: 4033
* Dislikes: 0
* Total Accepted: 395.8K
* Total Submissions: 989.1K
* Testcase Example: '[1,3]\n[2]'
*
* 给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
*
*
*
* 示例 1:
*
*
* 输入:nums1 = [1,3], nums2 = [2]
* 输出:2.00000
* 解释:合并数组 = [1,2,3] ,中位数 2
*
*
* 示例 2:
*
*
* 输入:nums1 = [1,2], nums2 = [3,4]
* 输出:2.50000
* 解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
*
*
* 示例 3:
*
*
* 输入:nums1 = [0,0], nums2 = [0,0]
* 输出:0.00000
*
*
* 示例 4:
*
*
* 输入:nums1 = [], nums2 = [1]
* 输出:1.00000
*
*
* 示例 5:
*
*
* 输入:nums1 = [2], nums2 = []
* 输出:2.00000
*
*
*
*
* 提示:
*
*
* nums1.length == m
* nums2.length == n
* 0
* 0
* 1
* -10^6
*
*
*
*
* 进阶:你能设计一个时间复杂度为 O(log (m+n)) 的算法解决此问题吗?
*
*/
// @lc code=start
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int n1 = nums1.size(), n2 = nums2.size();
if (n1 > n2) return findMedianSortedArrays(nums2, nums1);
// total取出k个数
int k = (n1 + n2 + 1) / 2;
int l = 0, r = n1;
while (l < r) {
int m1 = l + r >> 1;
int m2 = k - m1;
if (nums1[m1] < nums2[m2 - 1]) {
l = m1 + 1;
} else {
r = m1;
}
}
int m1 = l, m2 = k - l;
int c1 = max(m1 <= 0 ? INT_MIN : nums1[m1 -1],
m2 <= 0 ? INT_MIN : nums2[m2 - 1]);
int c2 = min(m1 >= n1 ? INT_MAX : nums1[m1],
m2 >= n2 ? INT_MAX : nums2[m2]);
if ((n1 + n2) & 1) {
return c1;
}
return (c1 + c2) * 0.5;
}
};
// @lc code=end