1.将数组排序,去重。直接返回前k个数。此种方法的弊端在于遇到较大的数组时,所有的数字都将放入内存中。
# -*- coding:utf-8 -*- class Solution: def GetLeastNumbers_Solution(self, tinput, k): # write code here sorted_input = list(set(sorted(tinput))) return sorted_input[:k] if k <= len(sorted_input) else []
2.建立一个k大小的数组,遍历n数组,每次将元素与k数组中最大的比较,如果小于k数组的最大值,则替换。重复直到完成这个遍历。
# -*- coding:utf-8 -*- class Solution: def GetLeastNumbers_Solution(self, tinput, k): # write code here min_kth = [] for num in tinput: if len(min_kth) < k and num not in min_kth: min_kth.append(num) elif min_kth and num < max(min_kth): min_kth = sorted(min_kth) min_kth[-1] = num return sorted(min_kth) if len(min_kth) == k else []
mark一下其它人的排序:
方法一:蒂姆排序
# -*- coding:utf-8 -*- class Solution: def GetLeastNumbers_Solution(self, tinput, k): # write code here if tinput == [] or k > len(tinput): return [] tinput.sort() return tinput[: k]
方法二:快速排序
# -*- coding:utf-8 -*- class Solution: def GetLeastNumbers_Solution(self, tinput, k): # write code here def quick_sort(lst): if not lst: return [] pivot = lst[0] left = quick_sort([x for x in lst[1: ] if x < pivot]) right = quick_sort([x for x in lst[1: ] if x >= pivot]) return left + [pivot] + right if tinput == [] or k > len(tinput): return [] tinput = quick_sort(tinput) return tinput[: k]
方法三:归并排序
# -*- coding:utf-8 -*- class Solution: def GetLeastNumbers_Solution(self, tinput, k): # write code here def merge_sort(lst): if len(lst) <= 1: return lst mid = len(lst) // 2 left = merge_sort(lst[: mid]) right = merge_sort(lst[mid:]) return merge(left, right) def merge(left, right): l, r, res = 0, 0, [] while l < len(left) and r < len(right): if left[l] <= right[r]: res.append(left[l]) l += 1 else: res.append(right[r]) r += 1 res += left[l:] res += right[r:] return res if tinput == [] or k > len(tinput): return [] tinput = merge_sort(tinput) return tinput[: k]
方法四:堆排序
# -*- coding:utf-8 -*- class Solution: def GetLeastNumbers_Solution(self, tinput, k): # write code here def siftup(lst, temp, begin, end): if lst == []: return [] i, j = begin, begin * 2 + 1 while j < end: if j + 1 < end and lst[j + 1] > lst[j]: j += 1 elif temp > lst[j]: break else: lst[i] = lst[j] i, j = j, 2 * j + 1 lst[i] = temp def heap_sort(lst): if lst == []: return [] end = len(lst) for i in range((end // 2) - 1, -1, -1): siftup(lst, lst[i], i, end) for i in range(end - 1, 0, -1): temp = lst[i] lst[i] = lst[0] siftup(lst, temp, 0, i) return lst if tinput == [] or k > len(tinput): return [] tinput = heap_sort(tinput) return tinput[: k]
方法五:冒泡排序
# -*- coding:utf-8 -*- class Solution: def GetLeastNumbers_Solution(self, tinput, k): # write code here def bubble_sort(lst): if lst == []: return [] for i in range(len(lst)): for j in range(1, len(lst) - i): if lst[j-1] > lst[j]: lst[j-1], lst[j] = lst[j], lst[j-1] return lst if tinput == [] or k > len(tinput): return [] tinput = bubble_sort(tinput) return tinput[: k]