Leetcode 215. Kth Largest Element in an Array

本文介绍了解决LeetCode 215题“数组中的第K个最大元素”的两种方法。一种是使用STL的sort函数,时间复杂度为O(nlogn),另一种是自写快速排序算法,时间复杂度相同但实际运行时间较长。文章提供了详细的代码实现及性能对比。

Leetcode 215. Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

题目大意:在乱序的数组中找到第k大的数,注意是该数组排序后的第k个数字而不是第k个大的单独的数字。

解题思路:将数组由大到小排序,返回第k-1个数字。时间复杂度O(nlogn)。

代码说明:代码1直接调用sort函数耗时8ms。代码2自写快排,规定第一个元素为哨兵项耗时80ms。可以看出STL的优化还是很强大的。

代码1:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        sort(nums.begin(), nums.end());
        return nums[nums.size() - k];
    }
};

代码2:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        int left = 0, right = nums.size() - 1;
        while(true)
        {
            int idx = partition(nums, left, right);
            if(idx == k - 1)
                return nums[idx];
            if(idx > k - 1)
                right = idx - 1;
            else
                left = idx + 1;
        }
        return -1;
    }
private:
    int partition(vector<int>& nums, int left, int right){
        int temp = nums[left], l = left + 1, r = right;
        while(l <= r)
        {
            if(nums[l] < temp && nums[r] > temp)
                swap(nums[l++], nums[r--]);
            if(nums[l] >= temp)
                l++;
            if(nums[r] <= temp)
                r--;
        }
        swap(nums[left], nums[r]);
        return r;
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值