- κ²¨μ° νκΈ°λ νλλ° μμ§ upper boundλ₯Ό ꡬνλ λΆλΆμ λͺ
ννκ² μ΄ν΄ λͺ»νκ±° κ°λ€.
- κΈ°λ³Έμ μΈ μμ΄λμ΄λ μλμ κ°λ€.
- μ€κ°κ°μ ν¬ν¨νλ arrayμ μ λ°μ ν΄λΉνλ μμΉλ₯Ό nums1, nums2μμ κ°κ° μ°Ύλλ€.
nums1
μ μ€κ°κ°μ ν¬ν¨νλ upper bound pos1
λ₯Ό μ€μ νλ€nums1[pos1]
κ°μ κΈ°μ€μΌλ‘ nums2
μμ upper bound λ₯Ό μ°Ύλλ€ = pos2
- λ§μΌ
pos1 + pos2
κ°μ΄ μ€κ°κ°μ ν¬ν¨νλ μμΉ upperHalf
λ³΄λ€ μκ±°λ ν¬λ©΄ κ·Έμ λ§μΆ μ μλλ‘ pos1
, pos2
λ₯Ό μ¦κ° λλ κ°μ μν¨λ€. - μ΄ λ μ¦κ°λ λ μμΉμ κ° μ€ μμ κ°μ κ°μ§ μͺ½, κ°μλ λ μμΉμ κ° μ€ ν° κ°μ κ°μ§ μͺ½μ λν΄μ μννλ€.
- μ€κ°κ°μ ꡬνλ€.
- μ 체 elementμ μκ° oddμΈ κ²½μ°
pos1
, pos2
λ κ° arrayμ upper boundμ΄λ―λ‘ nums1[pos1 - 1]
, nums2[pos2 - 1]
κ° μ€ ν° κ°μ μ€κ°κ°μΌλ‘ νλ€.
- μ 체 elementμ μκ° evenμΈ κ²½μ°
- upper boundλ λ κ°μ μ€κ°κ° μ¬μ΄μ κ±Έμ³ μλ€. λ°λΌμ upper bound μ΄μ μ κ° νλμ upper bound μμΉμ κ°μ νκ· λ΄μ΄ ꡬνλ€.
- λ array λͺ¨λ upper bound μ΄μ μ elementκ° μλ κ²½μ°
(
max(nums1[pos1 - 1], nums2[pos2 - 1])
+ min(nums1[pos1], nums2[pos2])
) / 2
- nums1μλ§ upper bound μ΄μ μ elementκ° μλ κ²½μ°
( nums1[pos1 - 1] + min(nums1[pos1], nums2[pos2]) ) / 2
- nums2μλ§ upper bound μ΄μ μ elementκ° μλ κ²½μ°
( nums2[pos2 - 1] + min(nums1[pos1], nums2[pos2]) ) / 2
class Solution {
public:
static constexpr int MIN_NUM = -1000000;
static constexpr int MAX_NUM = 1000000;
static inline int get(vector<int>& nums, int index, int defVal) {
return index >= 0 && index < nums.size()
? nums[index] : defVal;
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int M = nums1.size(), N = nums2.size();
bool even = (M + N) % 2 == 0;
int upperHalf = (M + N + 1) / 2;
int pos1 = (M + 1) / 2;
auto itr = upper_bound(
nums2.begin(), nums2.end(),
get(nums1, pos1, MAX_NUM + 1));
int pos2 = itr - nums2.begin();
while (pos1 + pos2 > upperHalf) {
auto a = get(nums1, pos1 - 1, MIN_NUM - 1);
auto b = get(nums2, pos2 - 1, MIN_NUM - 1);
if (a > b) --pos1;
else --pos2;
}
while (pos1 + pos2 < upperHalf) {
auto a = get(nums1, pos1, MAX_NUM + 1);
auto b = get(nums2, pos2, MAX_NUM + 1);
if (a < b) ++pos1;
else ++pos2;
}
if (even) {
int a = 0, b = 0;
if (pos1 > 0 && pos2 > 0) {
a = max(
get(nums1, pos1 - 1, MIN_NUM - 1),
get(nums2, pos2 - 1, MIN_NUM - 1)
);
b = min(
get(nums1, pos1, MAX_NUM + 1),
get(nums2, pos2, MAX_NUM + 1)
);
} else if (pos1 > 0) {
a = nums1[pos1 - 1];
b = min(
get(nums2, 0, MAX_NUM + 1),
get(nums1, pos1, MAX_NUM + 1)
);
} else {
a = min(
get(nums1, 0, MAX_NUM + 1),
get(nums2, pos2, MAX_NUM + 1)
);
b = nums2[pos2 - 1];
}
return (a + b) / 2.0;
} else {
return max(
get(nums1, pos1 - 1, MIN_NUM - 1),
get(nums2, pos2 - 1, MIN_NUM - 1)
);
}
}
};