前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【python刷题】多个有序数组

【python刷题】多个有序数组

作者头像
西西嘛呦
发布2021-02-25 16:24:16
2490
发布2021-02-25 16:24:16
举报

合并两个排序数组

代码语言:javascript
复制
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 res

A = [1,2,5,7,9]
B = [2,4,6,8,10,11,34,55]
res = mergeList(A, B)
print(res)

合并多个有序列表

代码语言:javascript
复制
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 res

lists = [[1,2,5,7,9],[2,4,6,8,10,11,34,55],[1,3,5,8,10,15]]
res = mergeMultiList(lists)
print(res)

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

代码语言:javascript
复制
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]))
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-02-07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 合并两个排序数组
  • 合并多个有序列表
  • 寻找两个有序列表中的中位数
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档