美文网首页
Median of Two Sorted Arrays

Median of Two Sorted Arrays

作者: 瞬铭 | 来源:发表于2019-02-22 11:35 被阅读0次
    1. 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)).
    
    You may assume nums1 and nums2 cannot be both empty.
    
    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
    

    暴力

    <?php
    
    
    class Solution {
    
        /**
         * @param Integer[] $nums1
         * @param Integer[] $nums2
         * @return Float
         */
        function findMedianSortedArrays($nums1, $nums2) {
            $arr = array_merge($nums1, $nums2);
            sort($arr);
            $len = count($arr);
            return ($len % 2 == 0) ? ($arr[$len / 2 - 1] + $arr[$len / 2]) / 2 : $arr[$len / 2];
        }
    
       
    
    $num1  = array(1, 3);
    $num2  = array(2);
    $class = new Solution();
    $res   = $class->findMedianSortedArrays($num1, $num2);
    var_dump($res);
    

    相关文章

      网友评论

          本文标题:Median of Two Sorted Arrays

          本文链接:https://www.haomeiwen.com/subject/vlusyqtx.html