zoukankan      html  css  js  c++  java
  • 剑指offer 面试40题

    面试40题:

    题目:最小的k个数

    题:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

    解题代码一:

    # -*- coding:utf-8 -*-
    class Solution:
        def GetLeastNumbers_Solution(self, tinput, k):
            # write code here
            #此方法时间复杂度为O(nlogn)
            if k >len(tinput):
                return []
            tinput.sort()
            return tinput[:k]

    解题代码二:

    # -*- coding:utf-8 -*-
    class Solution:
        def GetLeastNumbers_Solution(self, tinput, k):
            # write code here
            import heapq
            #此方法时间复杂度为O(nlogk)
            if k >len(tinput):
                return []
            return heapq.nsmallest(k,tinput)

    解题代码三:另:自己实现快速排序

    # -*- coding:utf-8 -*-
    class Solution:
        def GetLeastNumbers_Solution(self, tinput, k):
            # write code here
            #此方法时间复杂度为O(nlogn)
            if k >len(tinput) or not tinput:
                return []
            #tinput.sort()
            #实现一个快速排序
            def quick_sort(array):
                if not array:
                    return []
                pivot=array[0]
                left=quick_sort([x for x in array[1:] if x<pivot])
                right=quick_sort([x for x in array[1:] if x>=pivot])
                return left+[pivot]+right
            
            return quick_sort(tinput)[:k]
  • 相关阅读:
    hdu3336 Count the string 扩展KMP
    hdu3294 Girls' research manacher
    hdu3068 最长回文 manacher
    hdu2886 Lou 1 Zhuang 数学/快速幂
    hdu2841 Visible Trees 容斥原理
    hdu2819 Swap 二分图匹配
    RandomAccess接口的使用
    java集合框架
    java集合简介
    JDK,JRE,JVM的区别与联系
  • 原文地址:https://www.cnblogs.com/yanmk/p/9222971.html
Copyright © 2011-2022 走看看