4. Median of Two Sorted Arrays
来源:互联网 发布:php实例教程 编辑:程序博客网 时间:2024/06/16 11:00
题目
题目链接
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)).
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.5f
解析
翻译了Solution
把数组A和数组B分别拆分成两边:
因为数组A有m个数,所以一共有m+1中分割的方法。
求中位数,即:
m+n是偶数时:
m+n是奇数时(把中位数放在左边):
即(先不考虑边界情况):
这很巧妙,j的表达式包括了m+n为奇数和偶数的两种情况。
&& B[j−1]≤A[i] and A[i−1]≤B[j] $$
当下,我们所需要做的就是令i从0遍历到m,以找到一个i使得$B[j−1]≤A[i]&&A[i−1]≤B[j]$,此时$j=(m+n+1)/2−i$
现在可以使用二分查找了。最开始的i的区间是[0, m],后来不断二分,缩小结果i所应当在的区间[imin, imax]。对每一轮新的循环,都令
1. B[j−1]≤A[i] && A[i−1]≤B[j] —— 找到i,解决问题
2. B[j−1]>A[i] —— 增大i(即减小j),改变搜索区间为[imin = i+1, imax]
3. A[i−1]>B[j] —— 减小i,改变[imin,imax = i−1]
当找到i,最终结果即为:
m+n是偶数时:
m+n是奇数时(把中位数放在左边):
现在考虑边界情况:
溜了,午睡zzZ…
- [LeetCode]4.Median of Two Sorted Arrays
- LeetCode 4. Median of Two Sorted Arrays
- LeetCode --- 4. Median of Two Sorted Arrays
- [Leetcode] 4. Median of Two Sorted Arrays
- 4.Median of Two Sorted Arrays
- [LeetCode]4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 【leetcode】4. Median of Two Sorted Arrays
- Leetcode-4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- LeetCode-4.Median of Two Sorted Arrays
- leetcoode 4. Median of Two Sorted Arrays
- Leetcode 4. Median of Two Sorted Arrays
- leetcode 4. Median of Two Sorted Arrays
- Dialog
- 泛型 JFrame
- hibernate的检索策略
- MySQL数据库备份和恢复(咋个办呢 zgbn)
- python 获取utc时间转化为本地时间
- 4. Median of Two Sorted Arrays
- CSDN-markdown 编辑器使用说明
- 图片播放器小项目(详解)
- Oracle表空间(tablespaces)
- 数据结构——稀疏矩阵的十字链表表示方法
- 做好网站优化的18条建议
- AndroidTTT
- web安全测试
- JavaScript