Front k large number-Lintcode

Source: Internet
Author: User
Tags lintcode

Find the number of the top K in an array

Examples
Give [3,10,1000,-99,4,100], k = 3.
Back [1000, 100, 10]

Ideas
Build the minimum heap que. Traversal array nums, for element C, if the size of the que is less than k, directly add C; otherwise, compare the size of C and que heap tops, if C is large, to ensure the first k maximum, the top element of the heap pops up, add element C.

#ifndef c544_h #define C544_H #include <iostream> #include <vector> #include <queue> #include <
Functional> using namespace std; Class Solution {public:/** * @param nums:an integer array * @param k:an an integer * @return: the top k L  Argest numbers in array */vector<int> TOPK (vector<int> &nums, int k) {//write your code
        here if (Nums.empty ()) return nums;
        Normalized k value if (K > Nums.size ()) K = Nums.size ();
        Priority_queue<int,vector<int>,greater<int>> que;//constructs the smallest heap vector<int> res; When the size of the que is less than k, add the element c//Otherwise, compare the size of the C with the minimum heap heap top value, if C is large, eject the top element of the heap, add element c for (auto C:nums) {if (q
            Ue.size () < K) Que.push (c);
                    else {if (C>que.top ()) {Que.pop ();
                Que.push (c);
 }
            }       ///Insert the top element of the heap into the head of the res while (!que.empty ()) {Res.insert (Res.begin (), Que.top ());
        Que.pop ();
    return res;
}
}; #endif

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.