Skip to content

Instantly share code, notes, and snippets.

@ahmedeltaher
Created October 3, 2021 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmedeltaher/3ca9864b2b5cbd44fd1ffa9b038f0ca5 to your computer and use it in GitHub Desktop.
Save ahmedeltaher/3ca9864b2b5cbd44fd1ffa9b038f0ca5 to your computer and use it in GitHub Desktop.
215. Kth Largest Element in an Array
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>();
for(int num : nums){
maxHeap.add(num);
if(maxHeap.size()>k){
maxHeap.poll();
}
}
return maxHeap.poll();
}
}
// Time ==> O(nlog(k)), n ==> arraysize, k heap size
// Sapce ==> O(k)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment