【问题标题】:Sorting lists without .sort or sorted, solution in linear time在线性时间内对没有 .sort 或 sorted 的解决方案的列表进行排序
【发布时间】:2020-11-12 18:09:27
【问题描述】:

我正在做一些初学者 python 作业,这个野蛮的问题突然出现,我花了很多时间研究,但我没有发现任何有用的东西,但我觉得答案可能比什么更简单'到目前为止发现。 练习:

# 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.
# The solution should work in "linear" time, making a single
# pass of both lists.
# Hint: Don't use `sort` or `sorted` -- they are not O(n)
# linear time and the two lists are already provided in
# ascending sorted order.

如果您能提供一些有关该主题的文档,我将不胜感激,谢谢。

【问题讨论】:

  • 在归并排序算法中查找归并步骤
  • 这是“合并排序”中的“合并”操作。 i 是一个列表中的位置,j 是另一个列表中的位置。两者都从0 开始。每次“获取”一个元素时,都会增加位置。在您到达一个列表的末尾后,您可以从另一个列表中获取所有内容。
  • 已经在 stackoverflow 中讨论过

标签: python python-3.x algorithm sorting


【解决方案1】:

取 2 个迭代变量 i 和 j,每个列表一个,并在同一个循环中遍历它。
假设一个列表是 A = [2,5,6,9],另一个是 B = [1,4,7]。因此,为第一个列表 A 保留 i ,为 B 保留 j 一个新的空列表 C。 伪代码是这样的 -

i = 0
j = 0
C = list()
while(i<len(A) and j<len(B)):
    if(A[i]<B[j]):
        #Append the number to C
        C.append(A[i])
        i+=1
    elif(A[i]>B[j]):
        C.append(B[j])
        j+=1
    else:
        #Both equal, so add both to C
        C.append(A[i])
        C.append(B[j])
        i+=1
        j+=1

现在,如果 i 或 j 分别小于 len(A) 或 len(B),则将该数组的所有剩余元素添加到新数组 C。即,如果有任何其他元素未添加到 C列表,然后将它们添加到列表 C。您可以通过将 i 和 j 与其列表的各自长度进行比较来检查这一点。

如需更多说明,请告诉我。

【讨论】:

    【解决方案2】:

    一直在努力,这就是我最终的结果,似乎工作正常

    def linear_merge(list1, list2):
        list = []
        while list1 and list2:
            if list1[0] > list2[0]:
                list.append(list2[0])
                list2.remove(list2[0])
            else:
                list.append(list1[0])
                list1.remove(list1[0])
        if list1:
            list += list1
        elif list2:
            list += list2
        return list
    

    【讨论】:

      猜你喜欢
      • 2021-11-27
      • 2018-03-11
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多