215 Kth largest element in a array of K largest elements

Source: Internet
Author: User

Finds the largest element in an unordered array of the first K. Note that it is the nth largest element in an ordered array of arrays, not the K-different elements.
For example
Given [3,2,1,5,6,4] and k = 2, return 5.
Precautions:
You can assume that K is always valid, 1≤k≤ the length of the array.

See: https://leetcode.com/problems/kth-largest-element-in-an-array/description/

Method One:

Class Solution {public:    int findkthlargest (vector<int>& nums, int k) {        priority_queue<int,vector <int>,greater<int>> MinH;        for (int i=0;i<nums.size (); ++i)        {            if (minh.size () <k)            {                minh.push (nums[i]);            }            else            {                if (Minh.top () <nums[i])                {                    minh.pop ();                    Minh.push (Nums[i]);        }} return Minh.top ();    }};

Method Two:

Class Solution {public:    int partition (vector<int>& nums, int. left, int. right) {        int pivot = Nums[left];        int L = left + 1, r = right;        while (L <= r) {            if (Nums[l] < pivot && Nums[r] > Pivot)                swap (nums[l++], nums[r--]);            if (Nums[l] >= pivot) l++;             if (Nums[r] <= pivot) r--;        }        Swap (Nums[left], nums[r]);        return r;    }        int Findkthlargest (vector<int>& nums, int k) {        int left = 0, right = nums.size ()-1;        while (true) {            Int. pos = partition (Nums, left, right);            if (pos = = k-1) return Nums[pos];            if (pos > k-1) right = Pos-1;            else left = pos + 1;}}    ;

Reference: https://www.cnblogs.com/grandyang/p/4539757.html

215 Kth largest element in a array of K largest elements

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.