返回
与众不同——破解代码挑战:寻找两个有序数组的中位数
前端
2024-01-06 08:36:36
概述:
大家好,欢迎来到leetCode解题记录的第四期。今天,我们将共同探索寻找两个有序数组的中位数这一难题,并用JavaScript、TypeScript和Python三种语言来实现它。
挑战:
题目要求我们找到两个有序数组的中位数,且算法的时间复杂度必须为O(log(m + n))。这意味着我们不能简单地合并两个数组,然后再对合并后的数组进行排序,因为这会花费O(m + n)的时间。
策略:
为了满足时间复杂度的要求,我们可以采用一种更巧妙的方法。我们可以将两个数组视为一个整体,然后在整体上进行二分搜索。具体来说,我们可以从两个数组的中间位置开始,然后比较这两个中间值。如果这两个中间值相等,那么它们就是中位数。否则,我们可以根据这两个中间值的大小来确定中位数所在的数组,然后继续在该数组上进行二分搜索。
实现:
// JavaScript
const findMedianSortedArrays = (nums1, nums2) => {
const m = nums1.length;
const n = nums2.length;
const total = m + n;
let left = 0;
let right = m - 1;
while (left <= right) {
const i = Math.floor((left + right) / 2);
const j = Math.floor((total - 1 - i) / 2);
const nums1Left = nums1[i - 1] || Number.MIN_SAFE_INTEGER;
const nums1Right = nums1[i] || Number.MAX_SAFE_INTEGER;
const nums2Left = nums2[j - 1] || Number.MIN_SAFE_INTEGER;
const nums2Right = nums2[j] || Number.MAX_SAFE_INTEGER;
if (nums1Left <= nums2Right && nums2Left <= nums1Right) {
if (total % 2 === 0) {
return (Math.max(nums1Left, nums2Left) + Math.min(nums1Right, nums2Right)) / 2;
} else {
return Math.max(nums1Left, nums2Left);
}
} else if (nums1Left > nums2Right) {
right = i - 1;
} else {
left = i + 1;
}
}
};
// TypeScript
const findMedianSortedArrays = (nums1: number[], nums2: number[]): number => {
const m = nums1.length;
const n = nums2.length;
const total = m + n;
let left = 0;
let right = m - 1;
while (left <= right) {
const i = Math.floor((left + right) / 2);
const j = Math.floor((total - 1 - i) / 2);
const nums1Left = nums1[i - 1] || Number.MIN_SAFE_INTEGER;
const nums1Right = nums1[i] || Number.MAX_SAFE_INTEGER;
const nums2Left = nums2[j - 1] || Number.MIN_SAFE_INTEGER;
const nums2Right = nums2[j] || Number.MAX_SAFE_INTEGER;
if (nums1Left <= nums2Right && nums2Left <= nums1Right) {
if (total % 2 === 0) {
return (Math.max(nums1Left, nums2Left) + Math.min(nums1Right, nums2Right)) / 2;
} else {
return Math.max(nums1Left, nums2Left);
}
} else if (nums1Left > nums2Right) {
right = i - 1;
} else {
left = i + 1;
}
}
};
# Python
def find_median_sorted_arrays(nums1, nums2):
m = len(nums1)
n = len(nums2)
total = m + n
left = 0
right = m - 1
while left <= right:
i = (left + right) // 2
j = (total - 1 - i) // 2
nums1_left = nums1[i - 1] if i > 0 else float('-inf')
nums1_right = nums1[i] if i < m - 1 else float('inf')
nums2_left = nums2[j - 1] if j > 0 else float('-inf')
nums2_right = nums2[j] if j < n - 1 else float('inf')
if nums1_left <= nums2_right and nums2_left <= nums1_right:
if total % 2 == 0:
return (max(nums1_left, nums2_left) + min(nums1_right, nums2_right)) / 2
else:
return max(nums1_left, nums2_left)
elif nums1_left > nums2_right:
right = i - 1
else:
left = i + 1
return None
总结:
希望今天的分享能对大家有所帮助。如果大家在解题过程中遇到任何问题,欢迎随时留言。我们一起努力,共同进步!