博客
关于我
【python刷题】多个有序数组
阅读量:470 次
发布时间:2019-03-06

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

合并两个排序数组

def mergeList(A, B):    s1 = len(A)    s2 = len(B)    i,j = 0,0    res = []    while i < s1 and j < s2:        if A[i] <= B[j]:            res.append(A[i])            i += 1        else:            res.append(B[j])            j += 1    res = res + A[i+1:] + B[j+1:]    return resA = [1,2,5,7,9]B = [2,4,6,8,10,11,34,55]res = mergeList(A, B)print(res)

合并多个有序列表

def mergeMultiList(lists):    import heapq    from collections import deque    lists = list(map(lambda x: deque(x), lists))    pq = []    for ind, val in enumerate(lists):        pq.append((val.popleft(), ind))    heapq.heapify(pq)    res = []    while pq:        value, index = heapq.heappop(pq)        print(value, index)        res.append(value)        if lists[index]:            heapq.heappush(pq, (lists[index].popleft(), index))    return reslists = [[1,2,5,7,9],[2,4,6,8,10,11,34,55],[1,3,5,8,10,15]]res = mergeMultiList(lists)print(res)

寻找两个有序列表中的中位数

class Solution:    """    @param A: An integer array.    @param B: An integer array.    @return: a double whose format is *.5 or *.0    """    def findMedianSortedArrays(self, A, B):        n = len(A) + len(B)        if n % 2 == 1:            return self.findKth(A, B, n / 2 + 1)        else:            smaller = self.findKth(A, B, n / 2)            bigger = self.findKth(A, B, n / 2 + 1)            return (smaller + bigger) / 2.0    def findKth(self, A, B, k):        if len(A) == 0:            return B[int(k - 1)]        if len(B) == 0:            return A[int(k - 1)]        if k == 1:            return min(A[0], B[0])        a = A[int(k / 2) - 1] if len(A) >= k / 2 else None        b = B[int(k / 2) - 1] if len(B) >= k / 2 else None        if b is None or (a is not None and a < b):            return self.findKth(A[int(k / 2):], B, int(k - k // 2))        return self.findKth(A, B[int(k / 2):], int(k - k // 2))s = Solution()print(s.findMedianSortedArrays([1, 2, 3, 4, 5, 6], [2, 3, 4, 5]))

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

你可能感兴趣的文章
LiveGBS user/save 逻辑缺陷漏洞复现(CNVD-2023-72138)
查看>>
localhost:5000在MacOS V12(蒙特利)中不可用
查看>>
mac mysql 进程_Mac平台下启动MySQL到完全终止MySQL----终端八步走
查看>>
Mac OS 12.0.1 如何安装柯美287打印机驱动,刷卡打印
查看>>
MangoDB4.0版本的安装与配置
查看>>
Manjaro 24.1 “Xahea” 发布!具有 KDE Plasma 6.1.5、GNOME 46 和最新的内核增强功能
查看>>
mapping文件目录生成修改
查看>>
MapReduce程序依赖的jar包
查看>>
mariadb multi-source replication(mariadb多主复制)
查看>>
MaterialForm对tab页进行隐藏
查看>>
Member var and Static var.
查看>>
memcached高速缓存学习笔记001---memcached介绍和安装以及基本使用
查看>>
memcached高速缓存学习笔记003---利用JAVA程序操作memcached crud操作
查看>>
Memcached:Node.js 高性能缓存解决方案
查看>>
memcache、redis原理对比
查看>>
memset初始化高维数组为-1/0
查看>>
Metasploit CGI网关接口渗透测试实战
查看>>
Metasploit Web服务器渗透测试实战
查看>>
Moment.js常见用法总结
查看>>
MongoDB出现Error parsing command line: unrecognised option ‘--fork‘ 的解决方法
查看>>