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.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.

解决这种问题方法的核心还是排序,就比谁家排序方法更快了2333。。
三种方法:快排、priority_queue、标准库里的sort方法。
如果没有shuffle函数,运行时间是26ms,添加了以后是13ms。这个用咱大二的《数据结构与程序设计》中的快排方法理解起来嗖嗖快,解这题没必要完全排序,利用核心思想找出第K大的数就可以了。

快排

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        //STL中的函数random_shuffle()用来对一个元素序列进行重新排序(随机的)
        random_shuffle(nums.begin(), nums.end());
        int low = 0, high = nums.size() - 1;
        while (1) {
            /*
            无需加以low < high的判断
            具体情况具体分析,以下代码中只要pivot == k - 1 就会返回数值
            一种最后的情况:只剩下一个数,执行一次partition后,pivot就是该数,之后即返回
            而不是像《数据结构》p353的示例代码,若没有low<high的判断
            会不断调用最终的partition,即使partition中的循环不执行
            */
            int pivot = partition(nums, low, high);
            if (pivot == k - 1) return nums[pivot];
            else if (pivot > k - 1) {
                high = pivot - 1;
            }
            else { // pivot < k - 1
                low = pivot + 1;
            }
        }
    }

    int partition(vector<int>& nums, int low, int high) {
        int pivot, last_small;
        pivot = nums[low];
        last_small = low;
        for (int i = low + 1; i <= high; i++) {
            if (nums[i] > pivot) {
                last_small++;
                swap(nums[i], nums[last_small]);
            }
        }
        swap(nums[last_small], nums[low]);
        return last_small;
    }
};

priority_queue

/*利用priority_queue的特性*/
class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        priority_queue<int> pq(nums.begin(), nums.end());
        for (int i = 1; i < k; i++) {
            pq.pop();
        }
        return pq.top();
    }
};

标准库大法好——sort()函数

/利用C++标准库的排序函数/

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

discussion中还有堆排序的,虽然去年学过,突然不想做了2333
怎么感觉我的博客画风有点歪了蛤蛤蛤蛤蛤蛤

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值