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);
        }
    }
};
相关推荐
淀粉肠kk几秒前
C++11列表初始化:{}的革命性进化
c++
zhooyu13 分钟前
C++和OpenGL手搓3D游戏编程(20160207进展和效果)
开发语言·c++·游戏·3d·opengl
HAPPY酷17 分钟前
C++ 和 Python 的“容器”对决:从万金油到核武器
开发语言·c++·python
茉莉玫瑰花茶1 小时前
C++ 17 详细特性解析(5)
开发语言·c++·算法
cpp_25011 小时前
P10570 [JRKSJ R8] 网球
数据结构·c++·算法·题解
cpp_25012 小时前
P8377 [PFOI Round1] 暴龙的火锅
数据结构·c++·算法·题解·洛谷
程序员老舅2 小时前
C++高并发精髓:无锁队列深度解析
linux·c++·内存管理·c/c++·原子操作·无锁队列
划破黑暗的第一缕曙光2 小时前
[C++]:2.类和对象(上)
c++·类和对象
墨雪不会编程2 小时前
C++之【深入理解Vector】三部曲最终章
开发语言·c++
cpp_25012 小时前
P9586 「MXOI Round 2」游戏
数据结构·c++·算法·题解·洛谷