zoukankan      html  css  js  c++  java
  • [LeetCode] 4. Median of Two Sorted Arrays.(两个有序数组的中位数)

    Description

    Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
    给定两有序数组 nums1nums2,二者的大小分别为 mn,返回这两组数的中位数。

    Follow up

    The overall run time complexity should be (O(log (m + n)))
    总时间复杂度应为 (O(log (m + n)))

    Examples

    Example 1

    Input: nums1 = [1,3], nums2 = [2]
    Output: 2.00000
    Explanation: merged array = [1,2,3] and median is 2.
    

    Example 2

    Input: nums1 = [1,2], nums2 = [3,4]
    Output: 2.50000
    Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
    

    Example 3

    Input: nums1 = [0,0], nums2 = [0,0]
    Output: 0.00000
    

    Example 4

    Input: nums1 = [], nums2 = [1]
    Output: 1.00000
    

    Example 5

    Input: nums1 = [2], nums2 = []
    Output: 2.00000
    

    Constraints

    • nums1.length == m
    • nums2.length == n
    • 0 <= m <= 1000
    • 0 <= n <= 1000
    • 1 <= m + n <= 2000
    • -106 <= nums1[i], nums2[i] <= 1e6

    Solution

    这题我也是看了题解才明白个大概。参考文章见后,代码如下:

    import kotlin.math.max
    import kotlin.math.min
    
    class Solution {
        fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double {
            // 该算法需保证 nums2 更大
            if (nums1.size > nums2.size) {
                return findMedianSortedArrays(nums2, nums1)
            }
    
            var iMin = 0
            var iMax = nums1.size
            val halfLen = (nums1.size + nums2.size + 1) / 2
    
            while (iMin <= iMax) {
                val i = (iMin + iMax) / 2
                val j = halfLen - i
                if (i < nums1.size && nums2[j - 1] > nums1[i]) {
                    iMin = i + 1
                } else if (i > 0 && nums1[i - 1] > nums2[j]) {
                    iMax = i - 1
                } else {
                    val maxOfLeft = when {
                        i == 0 -> nums2[j - 1]
                        j == 0 -> nums1[i - 1]
                        else -> max(nums1[i - 1], nums2[j - 1])
                    }
                    if ((nums1.size + nums2.size) % 2 == 1) {
                        return maxOfLeft.toDouble()
                    }
    
                    val minOfRight = when {
                        i == nums1.size -> nums2[j]
                        j == nums2.size -> nums1[i]
                        else -> min(nums1[i], nums2[j])
                    }
    
                    return (maxOfLeft + minOfRight) / 2.0
                }
            }
            
            return 0.0
        }
    }
    

    Reference

    1. https://zhuanlan.zhihu.com/p/70654378
  • 相关阅读:
    Beta冲刺——集合随笔
    Beta冲刺——用户调查报告
    Beta冲刺——总结
    Beta冲刺——代码规范、冲刺任务与计划
    Beta冲刺——Day 7
    Beta冲刺——Day 6
    Beta冲刺——Day 5
    Beta冲刺——Day 4
    Beta冲刺——Day3
    beta冲刺汇总
  • 原文地址:https://www.cnblogs.com/zhongju/p/14193046.html
Copyright © 2011-2022 走看看