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);
        }
    }
};
相关推荐
2401_884602271 小时前
程序人生-Hello’s P2P
c语言·c++
初中就开始混世的大魔王1 小时前
2 Fast DDS Library概述
c++·中间件·信息与通信
娇娇yyyyyy2 小时前
C++基础(6):extern解决重定义问题
c++
Neteen2 小时前
【数据结构-思维导图】第二章:线性表
数据结构·c++·算法
灰色小旋风3 小时前
力扣——第7题(C++)
c++·算法·leetcode
Ralph_Y4 小时前
C++网络:一
开发语言·网络·c++
程序猿编码4 小时前
探秘 SSL/TLS 服务密码套件检测:原理、实现与核心设计(C/C++代码实现)
c语言·网络·c++·ssl·密码套件
故事和你914 小时前
sdut-程序设计基础Ⅰ-实验二选择结构(1-8)
大数据·开发语言·数据结构·c++·算法·优化·编译原理
像素猎人5 小时前
数据结构之顺序表的插入+删除+查找+修改操作【主函数一步一输出,代码更加清晰直观】
数据结构·c++·算法
蜡笔小马5 小时前
32.Boost.Geometry 空间索引:R-Tree 接口详解
c++·boost·r-tree