LeetCode 4. Median of Two Sorted Arrays
2018-02-26 17:09
344 查看
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]
题目链接
题目描述
寻找两个数组的中位树
思路
这道题一开始没有想出来,从网上看的题解,领略到了递归的牛X之处。简单来说就是,每一次查找来缩小一半的范围。直到一个数组为0时,即可通过下标找到该值。
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]
题目链接
题目描述
寻找两个数组的中位树
思路
这道题一开始没有想出来,从网上看的题解,领略到了递归的牛X之处。简单来说就是,每一次查找来缩小一半的范围。直到一个数组为0时,即可通过下标找到该值。
public class MedianOfTwoList { int lena = 0 ; int lenb = 0; public double findMedianSortedArrays(int A[], int B[]) { lena = A.length; lenb = B.length; int sum = lena+lenb; if ( sum%2==1 ) { return getKthNumber(A, 0, B, 0, sum/2+1)*1.0; } else { float s = getKthNumber(A, 0, B, 0, sum/2); lena = A.length; lenb = B.length; float s2 = getKthNumber(A, 0, B, 0, sum/2+1) ; return (s+s2)/2.0; } } private int getKthNumber(int[] a,int sa,int[] b,int sb,int k) { if ( this.lena-sa >this.lenb-sb ) { int temp = this.lena; this.lena = this.lenb; this.lenb = temp; return getKthNumber(b, sb, a, sa, k); } else { if ( this.lena-sa==0 ) { return b[sb+k-1]; } else { int m = Integer.min(k/2, this.lena-sa); if ( m==0 ) { return a[sa]<b[sb]?a[sa]:b[sb]; } else { if ( a[sa+m-1]<b[sb+m-1] ) { return getKthNumber(a, sa+m, b, sb, k-m); } else { return getKthNumber(a, sa, b, sb+m, k-m); } } } } } }
相关文章推荐
- leetcode Median of Two Sorted Arrays
- LeetCode 4 Median of Two Sorted Arrays
- LeetCode Online Judge 题目C# 练习 - Median of Two Sorted Arrays
- Leetcode:Median of Two Sorted Arrays
- LeetCode 4 Median of Two Sorted Arrays
- LeetCode - 4 - Median of Two Sorted Arrays(两排序数组找第k大)
- [leetcode]Median of Two Sorted Arrays
- Leetcode题解 - 4. Median of Two Sorted Arrays
- LeetCode | Median of Two Sorted Arrays
- LeetCode Median of Two Sorted Arrays
- leetcode - Median of Two Sorted Arrays
- LeetCode 之 Median of Two Sorted Arrays
- leetcode 4 -- Median of Two Sorted Arrays
- Leetcode 4. Median of Two Sorted Arrays
- leetcode Median of Two Sorted Arrays
- LeetCode 4 : Median of Two Sorted Arrays ( C++ )
- [c++]LeetCode Median of Two Sorted Arrays问题
- [Leetcode] 4.Median of Two Sorted Arrays
- [LeetCode题解004]Median of Two Sorted Arrays
- leetcode Median of Two Sorted Arrays