From 00c4da227117222477fd90a6ad780ce0dfec0adf Mon Sep 17 00:00:00 2001 From: Akshat Jain <68468062+Aj12345616@users.noreply.github.com> Date: Sun, 2 Oct 2022 19:33:13 +0530 Subject: [PATCH] Kth Largest Element in an Array --- Kth Largest Element in an Array.cpp | 89 +++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 Kth Largest Element in an Array.cpp diff --git a/Kth Largest Element in an Array.cpp b/Kth Largest Element in an Array.cpp new file mode 100644 index 00000000..df8797a1 --- /dev/null +++ b/Kth Largest Element in an Array.cpp @@ -0,0 +1,89 @@ + + int findKthLargest(vector& nums, int k) + { + if( k == 1 ) + { + int mv = INT_MIN; + for( size_t i = 0; i < nums.size(); ++i) + mv = std::max(mv,nums[i]); + + return mv; + } + else + { + vector heap; + for( size_t i = 0; i < nums.size(); ++i) + pushHeap(heap, k, nums[i]); + + return heap[0]; + } + } + + void pushHeap(vector& heap, int k, int v) + { + // cout << "Push: " << v << endl; + + if( heap.size() == (size_t)k ) + { + if( v <= heap[0] ) + return; + + //Adjust Heap + heap[0] = v; + adjustHeap(heap, k, 0 ); + } + else + { + heap.push_back(v); + + // Build Heap + if( heap.size() == (size_t)k ) + { + for(int pos = k/2-1; pos >= 0; --pos) + { + int posL = 2*pos+1; + int posR = posL+1; + + if( heap[posL] < heap[pos] ) + { + swap( heap, posL, pos); + adjustHeap(heap, k , posL); + } + + if(posR < k && heap[posR] < heap[pos] ) + { + swap( heap, posR, pos); + adjustHeap(heap, k , posR); + } + } + + // cout << "Build: " << heap << endl; + } + } + } + + void adjustHeap(vector& heap, int k, int pos) + { + while (pos <= (k/2-1)) + { + int child = 2*pos+1; + + if( (child + 1) < k && heap[child] > heap[child+1]) + ++child; + + if( heap[pos] <= heap[child]) + break; + + swap( heap, pos, child); + pos = child; + } + + // cout << "Adjust: " << heap << endl; + } + + void swap(vector& heap, int a, int b) + { + int t = heap[a]; + heap[a] = heap[b]; + heap[b] = t; + }