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);
        }
    }
};
相关推荐
暗然而日章20 小时前
C++基础:Stanford CS106L学习笔记 4 容器(关联式容器)
c++·笔记·学习
巨人张20 小时前
C++火柴人跑酷
开发语言·c++
Gomiko1 天前
C/C++基础(四):运算符
c语言·c++
freedom_1024_1 天前
【c++】使用友元函数重载运算符
开发语言·c++
zmzb01031 天前
C++课后习题训练记录Day43
开发语言·c++
赖small强1 天前
【Linux C/C++开发】 GCC -g 调试参数深度解析与最佳实践
linux·c语言·c++·gdb·-g
CAE虚拟与现实1 天前
C/C++中“静态链接(Static Linking)” 和 “动态链接(Dynamic Linking)释疑
开发语言·c++·dll·动态链接库·lib库
fpcc1 天前
C++编程实践——标准库中容器存储目标分析
c++
包饭厅咸鱼1 天前
PatchCore-----训练,测试,c++部署 工业异常检测框架
开发语言·c++·视觉检测
许长安1 天前
C++ 多态详解:从静态多态到动态多态
开发语言·c++·经验分享·笔记