https://leetcode.com/problems/median-of-two-sorted-arrays/description/
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Example 1:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Constraints:
- nums1.length == m
- nums2.length == n
- 0 <= m <= 1000
- 0 <= n <= 1000
- 1 <= m + n <= 2000
- -106 <= nums1[i], nums2[i] <= 106
1. C
멘탈이 나간다 나가~~
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
double ans;
int i = 0;
int j = 0;
int idx = 0;
int* sort = (int*)malloc((nums1Size+nums2Size)*sizeof(int));
while(i<nums1Size && j<nums2Size){
if(nums1[i]<nums2[j]){
sort[idx++] = nums1[i++];
}else{
sort[idx++] = nums2[j++];
}
}
if(i==nums1Size){
while(j!=nums2Size){
sort[idx++] = nums2[j++];
}
}else{
while(i!=nums1Size){
sort[idx++] = nums1[i++];
}
}
if(idx%2==1){ //sort -> add num
int med = idx/2;
ans = sort[med];
}else{
int med = idx/2;
ans = (sort[med]+sort[med-1])/2.0;
}
free(sort);
return ans;
}
코드를 짰지만 이건 log(M+N)을 만족하지 않고 O(M+N)의 방식이다.
뭐든 time을 log단위로 가져오려면, Binary Search를 써야한다.
그리고 문제의 Topic처럼 Divide&Conquer을 쓰는 것이 바람직하다.
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
// nums1은 항상 크기가 작은 배열이 되도록 합니다.
if (nums1Size > nums2Size) {
return findMedianSortedArrays(nums2, nums2Size, nums1, nums1Size);
}
int x = nums1Size;
int y = nums2Size;
int low = 0, high = x;
while (low <= high) {
int partitionX = (low + high) / 2;
int partitionY = (x + y + 1) / 2 - partitionX;
int maxX = (partitionX == 0) ? INT_MIN : nums1[partitionX - 1];
int maxY = (partitionY == 0) ? INT_MIN : nums2[partitionY - 1];
int minX = (partitionX == x) ? INT_MAX : nums1[partitionX];
int minY = (partitionY == y) ? INT_MAX : nums2[partitionY];
if (maxX <= minY && maxY <= minX) {
// 우리는 정확한 값을 찾았습니다.
if ((x + y) % 2 == 0) {
return ((double)fmax(maxX, maxY) + (double)fmin(minX, minY)) / 2;
} else {
return (double)fmax(maxX, maxY);
}
} else if (maxX > minY) {
high = partitionX - 1;
} else {
low = partitionX + 1;
}
}
// 입력이 잘못된 경우
return -1;
}
위와 같이 어떻게 푸냐 이거야..;;
2. C++
# C++ - binary search
class Solution {
public:
double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2) {
int n1 = nums1.size(), n2 = nums2.size();
// Ensure nums1 is the smaller array for simplicity
if (n1 > n2)
return findMedianSortedArrays(nums2, nums1);
int n = n1 + n2;
int left = (n1 + n2 + 1) / 2; // Calculate the left partition size
int low = 0, high = n1;
while (low <= high) {
int mid1 = (low + high) >> 1; // Calculate mid index for nums1
int mid2 = left - mid1; // Calculate mid index for nums2
int l1 = INT_MIN, l2 = INT_MIN, r1 = INT_MAX, r2 = INT_MAX;
// Determine values of l1, l2, r1, and r2
if (mid1 < n1)
r1 = nums1[mid1];
if (mid2 < n2)
r2 = nums2[mid2];
if (mid1 - 1 >= 0)
l1 = nums1[mid1 - 1];
if (mid2 - 1 >= 0)
l2 = nums2[mid2 - 1];
if (l1 <= r2 && l2 <= r1) {
// The partition is correct, we found the median
if (n % 2 == 1)
return max(l1, l2);
else
return ((double)(max(l1, l2) + min(r1, r2))) / 2.0;
}
else if (l1 > r2) {
// Move towards the left side of nums1
high = mid1 - 1;
}
else {
// Move towards the right side of nums1
low = mid1 + 1;
}
}
return 0; // If the code reaches here, the input arrays were not sorted.
}
};
3. Python
#Python - binary search
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
n1 = len(nums1)
n2 = len(nums2)
# Ensure nums1 is the smaller array for simplicity
if n1 > n2:
return self.findMedianSortedArrays(nums2, nums1)
n = n1 + n2
left = (n1 + n2 + 1) // 2 # Calculate the left partition size
low = 0
high = n1
while low <= high:
mid1 = (low + high) // 2 # Calculate mid index for nums1
mid2 = left - mid1 # Calculate mid index for nums2
l1 = float('-inf')
l2 = float('-inf')
r1 = float('inf')
r2 = float('inf')
# Determine values of l1, l2, r1, and r2
if mid1 < n1:
r1 = nums1[mid1]
if mid2 < n2:
r2 = nums2[mid2]
if mid1 - 1 >= 0:
l1 = nums1[mid1 - 1]
if mid2 - 1 >= 0:
l2 = nums2[mid2 - 1]
if l1 <= r2 and l2 <= r1:
# The partition is correct, we found the median
if n % 2 == 1:
return max(l1, l2)
else:
return (max(l1, l2) + min(r1, r2)) / 2.0
elif l1 > r2:
# Move towards the left side of nums1
high = mid1 - 1
else:
# Move towards the right side of nums1
low = mid1 + 1
return 0 # If the code reaches here, the input arrays were not sorted.