4. Median of Two Sorted Arrays

来源:互联网 发布:笙声入心网络剧百度云 编辑:程序博客网 时间:2024/05/22 17:43

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

Code

/** * @author liyiheng */public class Solution {    public double findMedianSortedArrays(int[] nums1, int[] nums2) {        int len1 = nums1.length;        int len2 = nums2.length;        int count = (len1 + len2) / 2 + 1;        int temp1 = 0, temp2 = 0;        int index1 = 0, index2 = 0;        for (int i = 0; i < count; i++) {            temp1 = temp2;            if (index1==len1){                // use 2                temp2 = nums2[index2];                index2++;            }else if (index2==len2){                // use 1                temp2 = nums1[index1];                index1++;            }else {                // use the smaller one                if (nums1[index1] < nums2[index2]) {                    temp2 = nums1[index1];                    index1++;                } else {                    temp2 = nums2[index2];                    index2++;                }            }        }         if ((len1+len2)%2!=0){            return temp2;        }      return   ((double) (temp1 + temp2))/2;    }}
0 0