LCR 076. 数组中的第 K 个最大元素

LCR 076. 数组中的第 K 个最大元素


题目链接:LCR 076. 数组中的第 K 个最大元素

下面这个题与这个题一样:

题目链接:215. 数组中的第K个最大元素

这个代码只能通过第一个题,如下:

cpp 复制代码
class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        quickSort(nums,0,nums.size()-1);
        return nums[nums.size()-k];
    }
	
	//快速排序
    void quickSort(vector<int>& nums,int low,int high)
    {
        if(low>=high)
            return;
        
        int partitionpivot=partition(nums,low,high);
        quickSort(nums,low,partitionpivot-1);
        quickSort(nums,partitionpivot+1,high);
    }

    int partition(vector<int>&nums,int low,int high)
    {
        int temp=nums[low];  
        while(low<high)
        {
            while(low<high&&nums[high]>=temp)
            high--;
            swap(nums[low],nums[high]);
            while(low<high&&nums[low]<=temp)
                low++;
            swap(nums[low],nums[high]);
        }
        nums[low]=temp;

        return low;
    }
};

这个代码两个题都能通过,如下:

cpp 复制代码
class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        vector<int> temp;
        temp.push_back(0);
        for(int i=0;i<nums.size();i++)
        {
            temp.push_back(nums[i]);
        }
        HeapSort(temp,nums.size());
        return temp[temp.size()-k];
    }

    //在含有n个元素的堆中添加一个元素,并调整为堆
    void HeadAdjust(vector<int>& arr, int i, int n)//调整为大根堆
    {
        arr[0] = arr[i];
        for (int j = 2 * i; j <= n; j *= 2)
        {
            if (j < n && arr[j] < arr[j + 1])
                j++;
            if (arr[j] <= arr[0])
                break;
            else
            {
                arr[i] = arr[j];
                i = j;
            }
        }
        arr[i] = arr[0];
    }

    void HeapSort(vector<int>& arr, int n)//递增排序
    {
        for (int i = n / 2; i > 0; i--)
            HeadAdjust(arr, i, n);

        for (int i = n; i > 1; i--)
        {
            swap(arr[1], arr[i]);
            HeadAdjust(arr, 1, i - 1);
        }
    }
};
相关推荐
汉克老师1 天前
GESP2025年3月认证C++五级( 第三部分编程题(1、平均分配))
c++·算法·贪心算法·排序·gesp5级·gesp五级
智者知已应修善业1 天前
【51单片机2个按键控制流水灯运行与暂停】2023-9-6
c++·经验分享·笔记·算法·51单片机
云泽8081 天前
C++11 核心特性全解:列表初始化、右值引用与移动语义实战
开发语言·c++
AI进化营-智能译站1 天前
ROS2 C++开发系列12-用多态与虚函数构建可扩展的ROS2机器人行为模块
开发语言·c++·ai·机器人
Morwit1 天前
QML组件之间的通信方案(暴露子组件)
c++·qt·职场和发展
qeen871 天前
【数据结构】建堆的时间复杂度讨论与TOP-K问题
c语言·数据结构·c++·学习·
图码1 天前
如何用多种方法判断字符串是否为回文?
开发语言·数据结构·c++·算法·阿里云·线性回归·数字雕刻
handler011 天前
Linux 内核剖析:进程优先级、上下文切换与 O(1) 调度算法
linux·运维·c语言·开发语言·c++·笔记·算法
zhouwy1131 天前
Linux进程与线程编程详解
linux·c++
A7bert7771 天前
【YOLOv8pose部署至RDK X5】模型训练→转换bin→Sunrise 5部署
c++·python·深度学习·yolo·目标检测