【问题标题】:Find kth largest element using quick select algorithm使用快速选择算法查找第 k 个最大元素
【发布时间】:2021-08-06 21:53:49
【问题描述】:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
    int partition(vector<int> &nums, int low,int high,int pivotElement)
    {
        int pivotPoint=low;
        for(int i=low;i<=high-1;i++)
        {
            if(nums[i]<=pivotElement)
            {
                swap(nums[i],nums[pivotPoint]);
                pivotPoint++;
            }
        }
        swap(nums[pivotPoint],pivotElement);
        return pivotPoint;
        
    }
    int quickSelect(vector<int> &nums, int k,int low,int high)
    {
        int pivotElement=nums[high];
        int pivot=partition(nums,low,high,pivotElement);
        if(pivot==k)
        {   
            return nums[pivot];
        }
        else if(pivot>k)
            return quickSelect(nums,k,low,pivot-1);
        else
        {   
            return quickSelect(nums,k,pivot+1,high);
        }
    }
    int findKthLargest(vector<int>& nums, int k) {
     return quickSelect(nums,nums.size()-k,0,nums.size()-1);
    }
};
int main(){
vector<int> v={3,2,1,5,6,4};
Solution ob;
cout<<ob.findKthLargest(v,2);
}

这是我的代码,我使用了快速选择算法。在这个问题中,我的目标是获得第 k 个最大的元素。尽管我试图涵盖所有内容并且通过了许多测试用例,但它在某些测试用例上给出了错误的答案。我尝试使用 cout 语句来获取错误,但根据我的试运行,我应该得到正确的输出。但是,当我尝试在第一个分区之后打印元素时,尽管根据交换,4 应该最终移动到索引 3 和 5,但那没有发生,4 仍然在最后,5 在索引 3 处。我无法弄清楚。请帮我解决这个问题。如果需要任何进一步的澄清,我会尽力以最好的方式解释这个问题,我很乐意提供。谢谢。

【问题讨论】:

  • 我不熟悉算法,但你的partition 函数按值接受nums,所以quickSelect 永远看不到这些变化。
  • 是的,我的错。非常感谢@BradyDean
  • 但它仍然给出不正确的输出
  • 我知道您将使用给定的选择算法。但在我看来,std::nth_element (en.cppreference.com/w/cpp/algorithm/nth_element) 会做你想要的,但更好。 . .

标签: c++ data-structures quickselect


【解决方案1】:

partition 中的swap 更改了局部变量 pivotElement 的值,该值不会传播回调用者。 (nums[pivotPoint] = pivotElement; 会得到同样的效果。)

您需要通过引用传递pivotElement,并直接传递nums[high] 以便更新nums[high]

int partition(vector<int> &nums, int low,int high,int &pivotElement)
// ...
// Later, in quickSelect
    int pivot=partition(nums,low,high,nums[high]);

【讨论】:

  • 为了使其正常工作,您需要将:return quickSelect(nums, nums.size() - k, 0, nums.size() - 1); 替换为 return quickSelect(nums, k, 0, nums.size() - 1);
猜你喜欢
  • 2021-06-07
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
  • 1970-01-01
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
  • 2017-06-23
相关资源
最近更新 更多