码迷,mamicode.com
首页 > 其他好文 > 详细

Median of Two Sorted Arrays

时间:2016-04-26 09:39:55      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

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)).

思路:题目要求是时间复杂度为O(log (m+n)).因此可能使用二分法。考虑二分法的本质,去掉一半一定不存在答案的一半. 题目要求的是两个排序数组中的Median number, 因此问题可以转化为,在两个排序数组中找从小到大的第K个数。关键的一点是判断nums1 的第K / 2 的数 与 nums2 的第 k / 2的数的大小关系来决定扔掉num1 的 前k/ 2 还是 num2 的前 k / 2.

相似的题目:Kth Largest Element in an Array

 1 public class Solution {
 2     public double findMedianSortedArrays(int[] nums1, int[] nums2) {
 3         int len = nums1.length + nums2.length;
 4         if (len % 2 == 1) {
 5             return findKth(nums1, 0, nums2, 0, len / 2 + 1);
 6         } else {
 7             return (findKth(nums1, 0, nums2, 0, len / 2) + findKth(nums1, 0, nums2, 0, len / 2 + 1)) / 2.0;
 8         }
 9         
10     }
11     
12     private int findKth(int[] A, int A_Start, int[] B, int B_Start, int k) {
13         if (A_Start >= A.length) {
14             return B[B_Start + k - 1];
15         }
16         if (B_Start >= B.length) {
17             return A[A_Start + k - 1];
18         }
19         if (k == 1) {
20             return Math.min(A[A_Start], B[B_Start]);
21         }
22         int keyA = A_Start + k / 2 - 1 < A.length ? A[A_Start + k / 2 - 1] : Integer.MAX_VALUE;
23         int keyB = B_Start + k / 2 - 1 < B.length ? B[B_Start + k / 2 - 1] : Integer.MAX_VALUE;
24         if (keyA > keyB) {
25             return findKth(A, A_Start, B, B_Start + k / 2, k - k / 2);
26         } else {
27             return findKth(A, A_Start + k / 2, B, B_Start, k - k / 2);
28         }
29     }
30 }

 

Median of Two Sorted Arrays

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5433699.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!