python - 如何合并两个列表并在 'linear' 时间内对它们进行排序?

标签 python list merge

我有这个,而且有效:

# E. Given two lists sorted in increasing order, create and return a merged
# list of all the elements in sorted order. You may modify the passed in lists.
# Ideally, the solution should work in "linear" time, making a single
# pass of both lists.
def linear_merge(list1, list2):
  finalList = []
  for item in list1:
    finalList.append(item)
  for item in list2:
    finalList.append(item)
  finalList.sort()
  return finalList
  # +++your code here+++
  return

但是,我真的很想学好这些东西。 :) “线性”时间是什么意思?

最佳答案

线性表示 Big O notation 中的 O(n) ,而您的代码使用的 sort() 很可能是 O(nlogn)

问题是要求 standard merge algorithm .一个简单的 Python 实现是:

def merge(l, m):
    result = []
    i = j = 0
    total = len(l) + len(m)
    while len(result) != total:
        if len(l) == i:
            result += m[j:]
            break
        elif len(m) == j:
            result += l[i:]
            break
        elif l[i] < m[j]:
            result.append(l[i])
            i += 1
        else:
            result.append(m[j])
            j += 1
    return result

>>> merge([1,2,6,7], [1,3,5,9])
[1, 1, 2, 3, 5, 6, 7, 9]

关于python - 如何合并两个列表并在 'linear' 时间内对它们进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2488889/

相关文章:

python - Graph-tool:如何访问add_edge_list返回的顶点值属性图?

python - 您如何在 Google App Engine 上进行自动化测试?

python - 遍历两个不同长度的列表

python - 连接列表 : Python 的元素

Android:如何混合 2 个音频文件并使用 soundPool 重现它们

windows - 可执行的merge.exe(从MSYS2中提取)未在Windows上运行

python - 在ROS中,如何将姿势从kinect框架转换为PR2的base_link框架?

python - 为什么这段代码表现得好像陷入了无限循环?

r - 将向量与 R 中具有多个条目的数据帧进行匹配

python - 使用最新的 PyDev 更新 Aptana Studio 3