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

LeetCode - Median of Two Sorted Arrays

时间:2018-05-21 10:29:28      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:over   时间复杂度   题目   2.0   lse   bsp   find   归并排序   ted   

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;
        }
    }
}

  

LeetCode - Median of Two Sorted Arrays

标签:over   时间复杂度   题目   2.0   lse   bsp   find   归并排序   ted   

原文地址:https://www.cnblogs.com/incrediblechangshuo/p/9065502.html

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