LeetCode 4 Median of Two Sorted Arrays
来源:互联网 发布:海量数据和数据港 编辑:程序博客网 时间:2024/06/09 15:21
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.5
每次在A,B取前k/2个元素。有以下这些情况:
1). A的元素个数不够k/2. 则我们可以丢弃B前k/2(因为此时A的所有元素+B前k/2的个数也不够k个,所以B的k/2肯定没有第k个元素)。反之亦然。
2). A[mid] < B[mid] (mid是k/2 -1)。这种情况下,我们可以丢弃A前k/2。
public double findMedianSortedArrays(int[] A, int[] B) {int len = A.length + B.length;if (len % 2 == 1)return findKey(A, B, 0, 0, len / 2 + 1);return (findKey(A, B, 0, 0, len / 2) + findKey(A, B, 0, 0,len / 2 + 1)) / 2.0;}public int findKey(int[] A, int[] B, int aStart, int bStart, int k) {if (aStart == A.length) return B[bStart + k - 1];if (bStart == B.length) return A[aStart + k - 1];if (k == 1) return Math.min(A[aStart], B[bStart]);int akey = aStart + k / 2 - 1 < A.length ? A[aStart + k / 2 - 1] : Integer.MAX_VALUE;int bkey = bStart + k / 2 - 1 < B.length ? B[bStart + k / 2 - 1] : Integer.MAX_VALUE;if (akey < bkey) return findKey(A, B, aStart + k / 2, bStart, k - k / 2);else return findKey(A, B, aStart, bStart + k / 2, k - k / 2);}
0 0
- 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
- [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
- [Leetcode]4Median 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
- 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
- LeetCode 4 - Median of Two Sorted Arrays
- leetcode 4 -- Median of Two Sorted Arrays
- effective stl 第18条: 避免使用vector<bool>
- hdu5869——Different GCD Subarray Query(思考+树状数组)
- windows环境下的socket nc 测试小工具nc -L -p 9999
- Python标准库简介
- CCF-201604-3-路径解析
- LeetCode 4 Median of Two Sorted Arrays
- hdu5873 Football Games(数学)(Landau's Theorem )
- java性能优化笔记(二)设计优化
- IOS 之 Quartz 2D 绘图(上)
- python爬虫之scrapy框架(一)
- HDU2544-最短路
- Appium基于安卓的元素定位方法
- hdu5869——Different GCD Subarray Query(思考+树状数组)
- 层次分析法的matlab的实现