数据结构与算法——随机选择算法

注:本文章只做个人记录

参考视频:

左程云--算法讲解024https://www.bilibili.com/video/BV1mN411b71K/?spm_id_from=333.1007.top_right_bar_window_history.content.click&vd_source=76d7f97a1ea3558ad70cf98b322a70c9

相关题目:

力扣215. 数组中的第K个最大元素https://leetcode.cn/problems/kth-largest-element-in-an-array/description/

1.随机选择算法求解数组中第K个最大元素
class Solution {
public:
    int findKthLargest(vector& nums, int k) {
        return randomizedSelect(nums, nums.size() - k);
    }

    int randomizedSelect(vector& nums, int k){
        int l = 0;
        int r = nums.size() - 1;
        int ans = 0;
        while(l <= r){
            int x = nums[l + rand() % (r - l + 1)];
            auto lmt = partition(nums, l, r, x);
            if(k < lmt.first){
                r = lmt.first - 1;
            }else if(k > lmt.second){
                l = lmt.second + 1;
            }else{
                ans = nums[k];
                break;
            }
        }
        return ans;
    }

    pair partition(vector& nums, int l, int r, int x){
        int a = l;
        int b = r;
        for(int i = l; i <= b; i++){
            if(nums[i] < x){
                swap(nums, a, i);
                a++;
            }else if(nums[i] > x){
                swap(nums, b, i);
                b--;
                i--;
            }
        }
        return {a, b};
    }

    void swap(vector& nums, int k, int i){
        int temp = nums[k];
        nums[k] = nums[i];
        nums[i] = temp;
    }
};

你可能感兴趣的:(算法,数据结构与算法,C++)