4. Median of Two Sorted Arrays

来源:互联网 发布:樱井知香喷泉原因 编辑:程序博客网 时间:2024/06/01 19:56

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

寻找两个有序数组的中位数

public class Solution {    public double findMedianSortedArrays(int[] nums1, int[] nums2) {        int m = nums1.length;        int n = nums2.length;        int i=0,j=0,k = 0;        int a=0,b=0;        while (k <= (m+n)/2) {            if (i < m && j < n) {                a = b;                b = nums1[i] < nums2[j] ? nums1[i++] : nums2[j++];            } else if (i < m) {                a = b;                b = nums1[i++];            } else if (j < n) {                a = b;                b = nums2[j++];            }            k++;        }        if ((m+n)%2 == 1) {            return (double) b;        } else {            return ((double)a + (double)b)/2;        }    }}
0 0
原创粉丝点击