zoukankan      html  css  js  c++  java
  • 4、两个有序序列的中位数。Median of Two Sorted Arrays

    题源:  https://leetcode.com/problemset/all/     第四题

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

    就是找出两个序列的中位数,时间复杂度为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
    

     我是这样做的..把两个序列合二为一,再直接找出中位数。上机试了一下可以。但是时间复杂度超出了题目限制。。。:

    double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
    
        int i=0,j=0,k=0,nums[nums1Size + nums2Size];
        while((i < nums1Size) && (j < nums2Size)){
            if(nums1[i] < nums2[j])
                nums[k++] = nums1[i++];
            else 
                nums[k++] = nums2[j++];
        }
        while(i < nums1Size) nums[k++] = nums1[i++];
        while(j < nums2Size) nums[k++] = nums2[j++];
        int n = nums1Size + nums2Size;
        if(n%2 == 1) return nums[n / 2];
        else return ((double)nums[n / 2] + (double)nums[(n-1) / 2]) / 2;
        
    }

    时间 和 空间 复杂度均为O(m+n).

    今天尝试在网站提交一次,通过了(如下图)...算是用了投机取巧的方法 。。

    网上还有其他的解题思路,有兴趣可以看一下。

     
  • 相关阅读:
    nsmutableset
    数组建立 不可变数组 排序 遍历
    字符串截取 拼接 转换 长度 查询 比较
    字典排序
    数字字典结合
    可变字典
    字典
    可变字符串
    oc block排序
    oc中文首字母排序
  • 原文地址:https://www.cnblogs.com/hozhangel/p/7739205.html
Copyright © 2011-2022 走看看