IncredibleThings

导航

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

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

 

题目要求time complexity 是O(log (m+n)), 先归并排序也是不可行的, 时间复杂度为O(m+n)

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        
        int l1 = nums1.length;
        int l2 = nums2.length;
        int i1 = 0;
        int i2 = 0;
        int i = 0;
        int[] nums = new int[l1+l2];
        while(i1 < l1 && i2 <l2){
            int num1 = nums1[i1];
            int num2 = nums2[i2];
            if(num1 < num2){
                nums[i] = num1;
                i1++;
            }
            else{
                nums[i] = num2;
                i2++;
            }
            i++;
        }
        if(i1 == l1){
            while(i2 < l2){
                nums[i]=nums2[i2];
                i2++;
                i++;
            }
        }
        else if(i2 == l2){
            while(i1 <l1){
                nums[i] = nums1[i1];
                i1++;
                i++;
            }
        }
        
        //find median
        if(i % 2 != 0){
            return (double)nums[i/2];
        }
        else{
            return ((double)nums[i/2-1] + (double)nums[i/2])/2;
        }
    }
}

  

posted on 2018-05-21 03:45  IncredibleThings  阅读(103)  评论(0编辑  收藏  举报