剑指offer:最小的k个数(C++/Python)

题目描述

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

C++

class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        vector<int>res;
        int len = input.size();
        if (len == 0 || k > len) return res;
        Qsort(input, 0, len - 1); //快排
        for (int i = 0; i < k; i++)
            res.push_back(input[i]);
        return res;
        
    }
    void Qsort(vector<int>&input, int left, int right)
    {
        int pivot;  //中轴位置
        if (left < right)
        {
            pivot = Partition(input, left, right);  //算出中轴位置
            //递归进行分割
            Qsort(input, left, pivot - 1);
            Qsort(input, pivot + 1, right);
        }
    }
    int Partition(vector<int>&input, int left, int right)
    {
        int temp, pivotkey;
        int i, j;
        pivotkey = input[left];  //以第一个元素为中轴元素
        i = left + 1;
        j = right;
        while (true)  //从表的两端交替的向中间扫描
        {
            //向右找到第一个大于等于 pivotkey 的元素位置
            while(i <= j && input[i] <= pivotkey)
                i++;
            //向左找到第一个小于等于 pivotkey 的元素位置
            while (i <= j && input[j] >= pivotkey)
                j--;
            if (i >= j) break;
            //交换,使得左边不大于pivotkey,右边不小于pivotkey
            temp = input[j];
            input[j] = input[i];
            input[i] = temp;
        }
        input[left] = input[j];
        input[j] = pivotkey;
        return j;
    }
};

Python

# -*- coding:utf-8 -*-
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        size = len(tinput)
        res = []
        if k > size:
            return res
        tinput.sort()
        for i in range(k):
            res.append(tinput[i])
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值