[LeetCode日记指南] 215. Kth Largest Element in an Array(多种方法)

题目描述

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example:
Input: “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

回溯法

回溯法(探索与回溯法)是一种选优搜索法,又称为试探法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。回溯法探索所有可能的候选组合找到所有解。

思路

经典的Google搜索排名算法,可用的解决方法有:

1)使用常规排序方法后找到数组中对应下标的值;
2)将数组内容存入一升序优先队列中,进行k-1次pop操作,那么队尾的元素就是第k大的数字;
3)使用数组内容构建一个最大堆/最小堆,通过每次pop出堆顶后继续维护堆的结构,直到满足一定的次数(最大堆k-1次,最小堆size-k次),堆顶的元素就是第k大的数字,实现的效果与优先队列相同;
4)利用快排的partition函数思想,选定一个数组内的值作为pivot,将小于pivot的数字放到pivot右边,大于等于pivot的数字放到pivot左边。接着判断两边数字的数量,如果左边的数量小于k个,说明第k大的数字存在于pivot及pivot右边的区域之内,对右半区执行partition函数;如果右边的数量小于k个,说明第k大的数字在pivot和pivot左边的区域之内,对左半区执行partition函数。直到左半区刚好有k-1个数,那么第k大的数就已经找到了。

代码与注释

//利用最大堆
class Solution {
    public:
        int findKthLargest(vector<int>& nums, int k) {
            //max heap method
            //min heap method
            //order statistics
            make_heap(nums.begin(), nums.end());
            int result;
            for(int i=0; i<k; i++){
                result=nums.front();
                pop_heap(nums.begin(), nums.end());
                nums.pop_back();
            }
            return result;
        }
    };
//利用优先队列
class Solution {
    public:
        int findKthLargest(vector<int>& nums, int k) {
            /** priority_queue<int, vector<int>, less<int>> q; **/
            priority_queue<int, vector<int>> q;
            int len=nums.size();
            for(int val:nums){
                q.push(val);
            }
            while(q.size() > len-k+1){
                q.pop();
            }
            return q.top();
        }
    };
//利用快排的思想
class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        int high = nums.size();
        int low = 0;
        int i, j;
        while (low < high) {
            i = low;
            j = high-1;
            int pivot = nums[low];
            while (i <= j) {
                while (i <= j && nums[i] >= pivot)
                    i++;
                while (i <= j && nums[j] < pivot)
                    j--;
                if (i < j)
                    swap(nums[i++],nums[j--]);
            }
            swap(nums[low],nums[j]);
            if (j == k-1)
                break;
            else if (j < k-1)
                low = j+1;
            else
                high = j;
        }
        return nums[j];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值