Advertisement
satishfrontenddev5

Untitled

Jan 6th, 2024
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. /*
  2. Find the kth smallest element in an unsorted array. Note that it is the kth smallest element in the sorted order, not the kth distinct element.
  3.  
  4. Input format
  5. First line contains an integer N - Number of elements in the array.
  6.  
  7. Second line contains N integers - The array elements.
  8.  
  9. Third line contains the integer k.
  10.  
  11. Output format
  12. Print the kth smallest element.
  13.  
  14. Sample Input 1
  15. 5
  16.  
  17. 8 5 3 8 5
  18.  
  19. 3
  20.  
  21. Sample Output 1
  22. 5
  23.  
  24. Explanation
  25. The elements in the sorted order are - 3,5,5,8,8. The 3rd smallest element is 5.
  26.  
  27. Constraints
  28. 1 <= k <= N <= 10^5
  29.  
  30. 0 <= array elements <= 10^9
  31. */
  32.  
  33. class KthSmallestElementInAnArray {
  34. public:
  35.     /*
  36.         priority_queue<int>pq;
  37.         int n=nums.size();
  38.         for(auto ele:nums){
  39.             pq.push(ele);
  40.         }
  41.         int result;
  42.         while(!pq.empty()){
  43.             if(pq.size()==(n-k+1))
  44.             return pq.top();
  45.             pq.pop();
  46.         }
  47.         return -1;
  48.     */
  49.     int findKthSmallest(vector<int>& nums, int k) {
  50.        sort(nums.begin(),nums.end());
  51.        return nums[k-1];
  52.     }
  53. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement