【leetcode】4. Median of Two Sorted Arrays

题目描述:

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

解题思路:

这道题个人觉得是很难的,要想解出这个题,就必须了解一下几点:

1.求一列长度为len的数字的中位数,其实也可以被看做是求第len/2小的数(len为奇),或者求第len/2,len/2 +1小的数的平均值的数(len为偶);

2.同时还要注意若想求两个有序数组array1和array2中第n小的数,则可以取a,b满足a+b=n,则如果array1[a-1]<array2[b-1],则array1[a]必然小于第n小的数。可以将这些数排除后,继续求剩余的数中第n-a小的数就是所要的答案;

3.要想很快的缩小一个数的值到所求值,用折半的方法可以减少循环次数。

代码如下:

 1 public class Solution {
 2     public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
 3         int len1=nums1.length;
 4         int len2=nums2.length;
 5         if(((len1+len2)&1)==0){
 6             int count=(len1+len2)/2;
 7             int num1=fun(nums1,0,nums2,0,count);
 8             int num2=fun(nums1,0,nums2,0,count+1);
 9             return (double)(num1+num2)/2;
10         }
11         else{
12             int count=(len1+len2)/2 +1;
13             int num=fun(nums1,0,nums2,0,count);
14             
15             return (double)num;
16         }
17     }
18      
19     public static int fun(int[] nums1,int from1,int[] nums2,int from2,int k){
20         //考虑到某个数组中的数已经全部被排除
21         if(from1>=nums1.length){
22             return nums2[from2+k-1];
23         }
24         if(from2>=nums2.length){
25             return nums1[from1+k-1];
26         }
27         //k=1即求最小,比较两个数组中的from位置处的值即可
28         if(k==1){
29             return nums1[from1]<nums2[from2]?nums1[from1]:nums2[from2];
30         }
31         //为了减少代码量,要保证nums1的长度要小于nums2的长度
32         if(nums1.length-from1>nums2.length-from2){
33             int[] nums=nums1;
34             int from=from1;
35             nums1=nums2;
36             from1=from2;
37             nums2=nums;
38             from2=from;
39         }
40         //nums1最好能截取k/2位置处的数,但要保证不能超过nums1中还存在的数的个数
41         int len1 = Math.min(nums1.length-from1, k/2);
42         //保证len1+len2=k;
43         int len2 = k -len1;
44         if(nums1[from1+len1-1]>=nums2[from2+len2-1]){
45             from2=from2+len2;
46             int result = fun(nums1,from1,nums2,from2,k-len2);
47             return result;
48         }
49         else{
50             from1=from1+len1;
51             int result = fun(nums1,from1,nums2,from2,k-len1);
52             return result;
53         }
54     
55     }
56 }
原文地址:https://www.cnblogs.com/godlei/p/5565678.html