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);
        }
    }
};
相关推荐
LyaJpunov9 天前
深入理解 C++ volatile 与 atomic:五大用法解析 + 六大高频考点
c++·面试·volatile·atomic
小灰灰搞电子9 天前
Qt PyQt与PySide技术-C++库的Python绑定
c++·qt·pyqt
时空自由民.9 天前
C++ 不同线程之间传值
开发语言·c++·算法
Ray_19979 天前
C++二级指针的用法指向指针的指针(多级间接寻址)
开发语言·jvm·c++
双叶8369 天前
(C语言)Map数组的实现(数据结构)(链表)(指针)
c语言·数据结构·c++·算法·链表·哈希算法
Jay_5159 天前
C++ STL 模板详解:由浅入深掌握标准模板库
c++·学习·stl
Cyrus_柯9 天前
C++(面向对象编程——继承)
开发语言·c++·算法·面向对象
Echo``9 天前
12.OpenCV—基础入门
开发语言·c++·人工智能·qt·opencv·计算机视觉
十秒耿直拆包选手9 天前
C++:动态库相关文件
c++
小L~~~9 天前
C++网络编程入门学习(五)-- CMake 学习笔记
linux·c++