LeetCode Brushing Notes-Data Structure-day20

LeetCode Brushing Notes-Data Structure-day20

215. The Kth Largest Element in an Array

1. Topic

Original title link: 215. The Kth largest element in an array

image-20220203093144515

2. Problem-solving ideas

Direct set of quick row templates:

void quick_sort(int q[], int l, int r)
{
    
    
    if (l >= r) return;

    int i = l - 1, j = r + 1, x = q[l + r >> 1];
    while (i < j)
    {
    
    
        do i ++ ; while (q[i] < x);
        do j -- ; while (q[j] > x);
        if (i < j) swap(q[i], q[j]);
    }
    quick_sort(q, l, j), quick_sort(q, j + 1, r);
}

3. Code

class Solution {
    
    
    public:
    int quickSort(vector<int>& nums,int l,int r,int k){
    
    
        if(l>=r) return nums[k];
        int x=nums[l+r>>1],i=l-1,j=r+1;
        while(i<j){
    
    
            do i++; while(nums[i]>x);
            do j--; while(nums[j]<x);
            if(i<j) swap(nums[i],nums[j]);
        }
        if(k<=j) return quickSort(nums,l,j,k);
        else return quickSort(nums,j+1,r,k);
    }
    int findKthLargest(vector<int>& nums, int k) {
    
    
        return quickSort(nums,0,nums.size()-1,k-1);
    }
};

347. Top K High Frequency Elements

1. Description of the topic

Original title link: 347. Top K high-frequency elements

image-20220203093219688

2. Problem-solving ideas

algorithm:哈希表+计数排序

Implementation:

  1. First use the hash table to count the number of occurrences of all numbers
  2. Use counting sorting to count the lower bound of the first k elements with the most occurrences
  3. Finally, traverse the hash table and add the number whose occurrences are greater than the lower bound to the answer

3. Code

class Solution {
    
    
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
    
    
        int n=nums.size();
        map<int,int> hash;
        for(auto x:nums) hash[x]++;
        vector<int> s(n+1);
        for(auto [a,b]:hash) s[b]++;
        int i=n,t=0;
        while(t<k) t+=s[i--];
        vector<int> res;
        for(auto [a,b]:hash){
    
    
            if(b>i) res.push_back(a);
        }
        return res;
    }
};

insert image description here

Guess you like

Origin blog.csdn.net/qq_45966440/article/details/122774418