Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. /******************************************************************************
  2.  
  3.                               Online C++ Compiler.
  4.                Code, Compile, Run and Debug C++ program online.
  5. Write your code in this editor and press "Run" button to compile and execute it.
  6.  
  7. *******************************************************************************/
  8.  
  9. #include <iostream>
  10. #include <vector>
  11. #include <algorithm>
  12. #include <queue>
  13.  
  14. using namespace std;
  15.  
  16. void PrintVector(const vector<int>& nums) {
  17.     for (int num : nums) {
  18.         std::cout << num << " ";
  19.     }
  20.     std::cout << std::endl;
  21. }
  22.  
  23. // Run-time complexity O(nlogn)
  24. // Memory complexity O(1)
  25. // In-place algorithm
  26. /*
  27. void PrintKLargest(vector<int>& nums, const int k) {
  28.    
  29.     sort(nums.begin(), nums.end(), greater<int>());
  30.    
  31.     for (int i = 0; i < k; ++i) {
  32.         std::cout << nums[i] << " ";
  33.     }
  34.    
  35.     std::cout << std::endl;
  36. }
  37. */
  38.  
  39. // Run-time complexity O(n)
  40. // Memory complexity O(1)
  41. // In-place algorithm
  42. /*
  43. void PrintKLargest(vector<int>& nums, const int k) {
  44.    
  45.     make_heap(nums.begin(), nums.end()); //O(3n) -> O(n)
  46.    
  47.     for (int i = 0; i < k; ++i) {
  48.         std::cout << nums.front() << " ";
  49.         pop_heap(nums.begin(), nums.end() - i); //O(2logn) -> O(logn)
  50.     }
  51.    
  52.     std::cout << std::endl;
  53. }
  54. */
  55.  
  56. // Run-time complexity O(n)
  57. // Memory complexity O(1)
  58. // In-place algorithm
  59. void PrintKLargest(vector<int>& nums, const int k) {
  60.    
  61.     //O(n)
  62.     priority_queue<int> heap(nums.begin(), nums.end());
  63.    
  64.     //O(klogn)
  65.     for (int i = 0; i < k; ++i) {
  66.         std::cout << heap.top() << " ";
  67.         heap.pop(); //pop_heap() + pop_back() O(logn) + O(1) -> O(logn)
  68.     }
  69. }
  70.  
  71.  
  72. int main()
  73. {
  74.     vector<int> nums = {1, 23, 12, 9, 30, 2, 50};
  75.    
  76.     int k = 5;
  77.    
  78.     PrintKLargest(nums, k);
  79.  
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement