剑指offer:最小的k个数
2019-07-08 23:37
1056 查看
题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
# -*- coding: utf-8 -*- # @Time : 2019-07-08 21:09 # @Author : Jayce Wong # @ProjectName : job # @FileName : getLeastNumbers.py # @Blog : https://blog.51cto.com/jayce1111 # @Github : https://github.com/SysuJayce class Solution: """ 从数组中寻找最小的k个数字,一般来说最直接的做法就是先将这个数组排序,然后取最小的k个数字即可。 但是这样做的时间复杂度为O(nlogn) 解法1: 借鉴快排中partition()的做法,因为partition()每次可以确定一个下标的正确元素,并保证其左右与其 大小关系有序。所以只要我们通过partition()确定了下标为k-1的元素,那么其左边都是小于该元素的。 时间复杂度为O(n) 解法2: 可以维护一个容量为k的容器,然后遍历整个数组,如果遇到比容器中最大值要小的元素,那么就将这个元素 替换容器中的最大值。时间复杂度为O(nlogk) """ def GetLeastNumbers_Solution1(self, tinput, k): if k <= 0 or k > len(tinput): return [] ans = tinput[:k] for i in range(k, len(tinput)): if tinput[i] < max(ans): ans.remove(max(ans)) ans.append(tinput[i]) return sorted(ans) def GetLeastNumbers_Solution2(self, tinput, k): def partition(begin, end): pos = begin for i in range(begin, end): if tinput[i] < tinput[end]: tinput[i], tinput[pos] = tinput[pos], tinput[i] pos += 1 tinput[end], tinput[pos] = tinput[pos], tinput[end] return pos if k <= 0 or k > len(tinput): return [] start, stop = 0, len(tinput) - 1 idx = partition(start, stop) while idx != k - 1: if idx > k: stop = idx - 1 else: start = idx + 1 idx = partition(start, stop) return sorted(tinput[: k]) def main(): nums = [4, 5, 1, 6, 2, 7, 3, 8] k = 4 solution = Solution() print(solution.GetLeastNumbers_Solution2(nums, k)) if __name__ == '__main__': main()
相关文章推荐
- 重做剑指offer(六)——旋转数组的最小数字
- 剑指Offer:最小的K个数Java/Python
- 剑指offer-面试题8.旋转数组的最小数字
- 剑指Offer - 九度1386 - 旋转数组的最小数字
- 剑指offer:把数组排成最小的数
- 剑指offer系列源码-把数组排成最小的数
- 最小的K个数 java实现 剑指offer
- 剑指offer(32)把数组排成最小的数
- 剑指offer第6题 ,旋转数组的最小值。
- 剑指offer:把数列排成最小的数
- 剑指offer 最小的K个数
- 剑指offer-最小的k个数
- 剑指offer_面试题40,最小的k个数,堆解法和快速选择解法
- 剑指offer之最小的k个数
- 《剑指offer》-旋转数组的最小数字
- 剑指Offer(45)把数组排成最小的数
- (php实现剑指offer)旋转数字的最小数字
- 《剑指offer》刷题笔记(查找和排序):旋转数组的最小数字
- 剑指offer:最小的k个数
- 《剑指Offer》之“旋转数组的最小数字”