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

[Leetcode] Median of Two Sorted Arrays

时间:2015-08-12 23:28:41      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

这个问题是求第K大的一个中特殊情况。

假设连个数组是A,B,我们分别求A和B的前m段和前n段,且m+n=k。

我们比较A[m-1] 和 B[n-1]

如果A[m-1] < B[n-1]则舍弃A的前m个元素,且现在需要找的是第k-m大的元素

相反,舍弃B的前n个元素,且现在需要找的是第k-n大的元素

 

关键是为什么呢?我们舍弃的部分可能是不包括第k大的,如果包括第k大,那么舍弃的部分小于等于第k大的元素加上另一个数组当中小于等于第k大的元素,元素个数之和一定是小于k的,这样是矛盾的,所以第k大一定不再被舍弃的部分当中。

 1 public class Solution {
 2     private int findkth(int []nums1, int start1, int s1, int [] nums2, int start2, int s2, int k){
 3         if(s1>s2) return findkth(nums2,start2,s2,nums1,start1,s1,k);
 4         if(s1==0) return nums2[start2+k-1];
 5         if(k==1) return Math.min(nums1[start1],nums2[start2]);
 6         int pa=Math.min(s1,k/2);
 7         int pb=k-pa;
 8         if(nums1[start1+pa-1]<nums2[start2+pb-1]){
 9             return findkth(nums1,start1+pa,s1-pa,nums2,start2,s2,k-pa);
10         }
11         else{
12             return findkth(nums1,start1,s1,nums2,start2+pb,s2-pb,k-pb);
13         }
14     }
15     public double findMedianSortedArrays(int[] nums1, int[] nums2) {
16         int m=nums1.length;
17         int n=nums2.length;
18         int mn=m+n;
19         if(mn%2==1){
20             //we should pay attention to the last parameter, it means the rank, other than the index, so it starts from 1 not 0.
21             int res=findkth(nums1,0,m,nums2,0,n,mn/2+1);
22             return (double)res;
23         }
24         else{
25             int res1=findkth(nums1,0,m,nums2,0,n,mn/2);
26             int res2=findkth(nums1,0,m,nums2,0,n,mn/2+1);
27             return ((double)res1+(double)res2)/2;
28         }
29     }
30 }

 

[Leetcode] Median of Two Sorted Arrays

标签:

原文地址:http://www.cnblogs.com/deepblueme/p/4725686.html

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