NOWCODER 剑指offer 最小的k个数

运行时间:33ms

占用内存:5712k

用sorted很简单

# -*- coding:utf-8 -*-
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        if k>len(tinput):
            return []
        tinput = sorted(tinput)
        return tinput[:k]

————————————————————————

如果不用sorted,想的是冒泡排序,冒k次泡即可

运行时间:38ms

占用内存:5720k

教训:Python中的交换只需要tinput[j],tinput[j-1] = tinput[j-1],tinput[j]即可

# -*- coding:utf-8 -*-
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        n = len(tinput)
        if k>n:
            return []
        for i in range(k):
            for j in range(n-1,i,-1):
                if tinput[j]<tinput[j-1]:
                    tinput[j],tinput[j-1] = tinput[j-1],tinput[j]
        return tinput[:k]

————————————————————————————————

标准答案里,把所有排序方法复习了一遍

1、冒泡排序,如上面程序所示,时间复杂度O(n*k)

2、蒂姆排序,如上上面程序所示,即Python自带的sorted排序(查不到)

猜你喜欢

转载自blog.csdn.net/u014381464/article/details/82112388