剑指offer--面试题30:最小的K个数



题目描述

输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
python实现:
# -*- coding:utf-8 -*-
class Solution:
    #法1:堆(大顶堆)
    def GetLeastNumbers_Solution1(self, tinput, k):
        # write code here
        n = len(tinput)
        if n==0 or k>n or k<=0:
            return []
        if n==k:
            return sorted(tinput)
 
        import heapq
        hq = []
        heapq.heapify(hq)
        for num in tinput:
            if len(hq)n or k<=0:
            return []
        if n==k:
            return sorted(tinput)
         
        low, high = 0, n-1
        idx = self.partition(tinput, low, high)
        while idx!=k-1:#因为下标从0开始计数,所以是k-1
            if idx>k-1:
                high = idx-1
                idx = self.partition(tinput, low, high)
            else:
                low = idx+1
                idx = self.partition(tinput, low, high)
                 
        return sorted(tinput[:k])
     
    def partition(self, nums, low, high):
        pivot = nums[low]
        while low=pivot:
                high -= 1
            nums[low] = nums[high]
            #low += 1#出错
            while low
c++实现:
class Solution {
public:
    //法1:堆
    vector GetLeastNumbers_Solution1(vector input, int k) {
        priority_queue hq;//默认是大顶堆(优先队列)
        vector result;
        if(input.empty() || k>input.size() || k<=0)
            return result;
        if(k==input.size()){
            sort(input.begin(), input.end());
            return input;
        }
          
        for(auto num : input){
            if(hq.size() GetLeastNumbers_Solution(vector input, int k) {
        //vector result;
        if(input.empty() || k>input.size() || k<=0)
            return {};
        if(k==input.size()){
            sort(input.begin(), input.end());
            return input;
        }
          
        int low=0, high=input.size()-1;
        int idx = partition(input, low, high);
        while(idx!=k-1){
            if(idx>k-1){
                high = idx-1;
                idx = partition(input, low, high);
            }else{
                low = idx+1;
                idx = partition(input, low, high);
            }
        }
          
        //for(int i=0; i result(input.begin(), input.begin()+k);
        //sort(result.begin(), result.end());
        return result;
    }
      
    int partition(vector &numbers, int low, int high){
        int pivot = numbers[low];
        while(low=pivot){
                high--;
            }
            numbers[low] = numbers[high];
            //numbers[low++] = numbers[high];
            while(low


你可能感兴趣的:(剑指offer)