leetcode 215 寻找数组中的第k大的值;

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

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

方法:

  • 快速排序的方法 根据index与k 的比较 循环;
  • 最大堆 弹出前几个
  • 优先队列 弹出前几个

方法1:快速排序的方法  partition找出基准的位置;判断基准与k的关系

   //1'quick_select
    int partition(vector<int>&nums,int left,int right)//我这里是从大到小排列的快速排序;也可以从小到大排列,但是 第k大的对应关系一定要弄懂喲!!
    {
        if(left>right)
            return 0;
        int pivort=nums[left];
        while(left<right)
        {
            while(left<right&&nums[right]<=pivort)//从大到小的排序;这个 right跟基准是left有关喲!!!
                right--;
            swap(nums[left],nums[right]);
            while(left<right&&nums[left]>=pivort)
                left++;
            swap(nums[left],nums[right]);
        }
        return left;
    }
    int findKthLargest(vector<int>& nums, int k)
    {
        int n=nums.size();
        assert(k>=1&&k<=n);
        int left=0;
        int right=n-1;
        
        while(1)//切记这里面有一个死循环哟;
        {
            int pos=partition(nums,left,right);
            if(pos+1==k) return nums[pos];
            else if(pos+1>k) right=pos-1;
            else    left=pos+1;
        }
        
        
    }

方法二:利用最大堆

  //2 、 heap
    int findKthLargest(vector<int>& nums, int k)
    {
        int n=nums.size();
        assert(k>=1&&k<=n);
        make_heap(nums.begin(),nums.end());
        int result=0;
        for(int i=0;i<k;i++)
        {
            result=nums.front();
            pop_heap(nums.begin(),nums.end());//注意这里面没有删除 元素 必须后面再删除哟!!!
            nums.pop_back();
        }
        return result;
    }

三:优先队列

 int findKthLargest(vector<int>& nums, int k)
    {
        int n=nums.size();
        assert(k>=1&&k<=n);
        priority_queue<int,vector<int>>q;
        for(auto val:nums)
            q.push(val);
        while(q.size()>n-k+1)
            q.pop();
        return q.top();
    }

猜你喜欢

转载自blog.csdn.net/langxue4516/article/details/81348575