博客
关于我
PTA 7-3 两个有序序列的中位数 (25 分)
阅读量:739 次
发布时间:2019-03-22

本文共 732 字,大约阅读时间需要 2 分钟。

为了求解两个非降序序列S1和S2的并集的中位数,我们可以使用双指针法来高效找到中位数。具体步骤如下:

  • 初始化两个指针i和j分别指向S1和S2的起始位置。
  • 计算目标位置m,使用公式m = (2n-1)//2,其中n是S1和S2的长度。
  • 使用循环遍历,直到i+j >= m。在每次循环中,比较S1[i]和S2[j]的大小,取较大的值,或者移动对应的指针。
  • 当进入循环结尾时,比较S1[i]和S2[j]的值,返回较大的一个作为中位数。
  • 通过这种方法,我们可以在O(n)的时间复杂度内找到并集的中位数,适合处理大数据量。

    步骤解释中的示例代码理解:

    def find_median(S1, S2):    n = len(S1)    i = j = 0    m = (2 * n - 1) // 2  # 目标索引    while i + j < m:        if S1[i] <= S2[j]:            i += 1        else:            j += 1    # 如果超出数组,直接返回最后一个数    # 否则比较剩下的数并返回较大的    return max(S1[i], S2[j] if i + j == m else S1[i], S2[j] if i + j == m else max(S1[i], S2[j]))n = int(input())S1 = list(map(int, input().split()))S2 = list(map(int, input().split()))print(find_median(S1, S2))

    代码逻辑简单明了,利用双指针法,高效地求得并集的中位数。

    转载地址:http://bkbwk.baihongyu.com/

    你可能感兴趣的文章
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    no1
    查看>>