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

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

合并两个有序数组

为了高效合并两个有序数组,我们可以采用双指针技术。具体步骤如下:

  • 初始化两个指针ij,分别指向两个数组的起始位置。
  • 在两个指针都未超出数组长度时,比较当前元素的大小:
    • 如果A[i]小于等于B[j],将A[i]加入结果数组,并移动i指针。
    • 否则,将B[j]加入结果数组,并移动j指针。
  • 当其中一个指针超出数组长度后,直接将剩余部分的元素加入结果数组。
  • 返回最终的合并数组。
  • 示例代码如下:

    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 += 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)

    合并多个有序列表

    当需要合并多个有序列表时,可以使用堆队列(优先队列)算法。具体步骤如下:

  • 将每个列表转换为队列,并将其元素及其原列表索引加入优先队列。
  • 对优先队列进行堆化,确保最小值总是首先被处理。
  • 重复以下步骤直到队列为空:
    • 取出队列中最小的元素value及其索引index
    • value添加到结果数组。
    • 如果对应的原列表不为空,则将其下一个元素加入队列。
  • 返回结果数组。
  • 示例代码如下:

    def mergeMultiList(lists):    import heapq    from collections import deque    lists = list(map(lambda x: deque(x), lists))    pq = []    for ind, val in enumerate(lists):        heapq.heappush(pq, (val, ind))    res = []    while pq:        value, index = heapq.heappop(pq)        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)

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

    为了找到两个有序列表的中位数,我们可以采用递归分治的方法。具体步骤如下:

  • 计算两个列表总长度n
    • 如果n为奇数,找到第n/2 + 1个元素作为中位数。
    • 如果n为偶数,找到第n/2n/2 + 1个元素的平均值作为中位数。
  • 实现findKth函数来定位第k个元素:
    • 如果某一列表为空,直接返回另一个列表的第k-1个元素。
    • 比较两个列表的中间元素,决定继续搜索哪一个列表。
  • 调用findKth函数来找到中位数。
  • 示例代码如下:

    class Solution:    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[k-1]        if len(B) == 0:            return A[k-1]        if k == 1:            return min(A[0], B[0])        a = A[k//2 - 1] if len(A) >= k//2 else None        b = B[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[k//2:], B, k - k//2)        return self.findKth(A, B[k//2:], k - k//2)

    测试示例:

    s = Solution()print(s.findMedianSortedArrays([1, 2, 3, 4, 5, 6], [2, 3, 4, 5]))

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

    你可能感兴趣的文章
    OpenAll:Android打开组件新姿势【仅供用于学习了解ButterKnife框架基本原理】
    查看>>
    OpenASR 项目使用教程
    查看>>
    Openbox-桌面图标设置
    查看>>
    opencart出现no such file or dictionary
    查看>>
    OpenCV 3.1 imwrite()函数写入异常问题解决方法
    查看>>
    OpenCV 4.1.0版drawContours
    查看>>
    Opencv cv2.putText 函数详解
    查看>>
    opencv glob 内存溢出异常
    查看>>
    opencv Hog Demo
    查看>>
    opencv Hog学习总结
    查看>>
    opencv Mat push_back
    查看>>
    opencv putText中文乱码
    查看>>
    OpenCV Python围绕特定点将图像旋转X度
    查看>>
    opencv resize
    查看>>
    Opencv Sift和Surf特征实现图像无缝拼接生成全景图像
    查看>>
    opencv SVM分类Demo
    查看>>
    OpenCV VideoCapture.get()参数详解
    查看>>
    opencv videocapture读取视频cap.isOpened 输出总是false
    查看>>
    opencv waitKey() 函数理解及应用
    查看>>
    OpenCV 中的图像转换
    查看>>