K Largest Element LeetCode
Approach 1:
Using ArrayList and Sorting
TIME : O(NLOGN) [LeetCode Time: 5 ms]
SPACE: O(N) [LeetCode Space 39.2MB]
class Solution {
public int findKthLargest(int[] arr, int k) {
ArrayList<Integer> aa=new ArrayList<Integer>();
for(int i=0;i<arr.length;i++){
aa.add(arr[i]);
}
Collections.sort(aa);
return (aa.get(aa.size()-k));
}
}
=========================================================================
Approach 2:
Using Priority Queue and getting the peak element
TIME: O(NLOGK) [LeetCode Time: 2ms]
SPACE: O(K) [LeetCode Space: 39.8MB]
class Solution {
public int findKthLargest(int[] arr, int k) {
PriorityQueue<Integer> q=new PriorityQueue<Integer>();
for(int i=0;i<k;i++){
q.add(arr[i]);
}
for(int i=k;i<arr.length;i++){
if(q.peek()<arr[i]){
q.remove();
q.add(arr[i]);
}
}
return q.peek();
}
}
Thanks for Reading.
"Knowledge grows by sharing not by saving.😇"
Please like, share, comment.
Comments
Post a Comment