Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Method 1
- /*
- Time complexity: O(nlogk)
- Auxiliary Space: O(logK)
- max_heap will store maximum of k minimum elements of the array
- */
- class Solution{
- public:
- int kthSmallest(int arr[], int l, int n, int k) {
- priority_queue<int> pq;
- for(int i = 0; i < k; i++) pq.push(arr[i]);
- for(int i = k; i <=n; i++){
- if(arr[i] < pq.top()){ //it is because we will keep k minimum elements in max_heap and maximum of that k we will be at top
- pq.pop(); //that will be our answer ie. kth minimum element
- pq.push(arr[i]);
- }
- }
- return pq.top();
- }
- };
- //Method 2
- //Quick select
- int partition(int arr[],int l,int r){
- int pivot=arr[r];
- int i=l,j=l;
- for(;i<r;i++){
- if(arr[i]<pivot){ swap(arr[i],arr[j]); j++;}
- }
- swap(arr[j],arr[r]);
- return j;
- }
- int quickselect(int arr[],int l,int r,int k){
- if(l<=r){
- int p=partition(arr,l,r);
- if(k==p) return arr[k];
- if(k<p) return quickselect(arr,l,p-1,k);
- else return quickselect(arr,p+1,r,k);
- }
- }
- class Solution{
- public:
- // arr : given array
- // l : starting index of the array i.e 0
- // r : ending index of the array i.e size-1
- // k : find kth smallest element and return using this function
- int kthSmallest(int arr[], int l, int r, int k) {
- //find element at k-1 position
- return quickselect(arr,l,r,k-1);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement