Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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.
- Input format
- First line contains an integer N - Number of elements in the array.
- Second line contains N integers - The array elements.
- Third line contains the integer k.
- Output format
- Print the kth smallest element.
- Sample Input 1
- 5
- 8 5 3 8 5
- 3
- Sample Output 1
- 5
- Explanation
- The elements in the sorted order are - 3,5,5,8,8. The 3rd smallest element is 5.
- Constraints
- 1 <= k <= N <= 10^5
- 0 <= array elements <= 10^9
- */
- class KthSmallestElementInAnArray {
- public:
- /*
- priority_queue<int>pq;
- int n=nums.size();
- for(auto ele:nums){
- pq.push(ele);
- }
- int result;
- while(!pq.empty()){
- if(pq.size()==(n-k+1))
- return pq.top();
- pq.pop();
- }
- return -1;
- */
- int findKthSmallest(vector<int>& nums, int k) {
- sort(nums.begin(),nums.end());
- return nums[k-1];
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement