Sorting Approach
Sorting Approach
python
Copy
def findKthLargest(nums, k):
# Sort the array in descending order
nums.sort(reverse=True)
# Return the k-th largest element
return nums[k-1]
Explanation:
Time Complexity:
Sorting the array takes O(n log n) time, where n is the number of elements in the
array.
The space complexity is O(1) if we ignore the space used by the sorting algorithm.
If we use a Min-Heap of size k, we can keep track of the k largest elements in the array
efficiently. In this case, the root of the Min-Heap will always be the smallest of the k largest
elements.
python
Copy
import heapq
Explanation:
Time Complexity:
Example Walkthrough:
Example 1:
Input:
python
Copy
nums = [3, 2, 1, 5, 6, 4]
k = 2
1. Sorting approach: After sorting the array in descending order, we get [6, 5, 4, 3,
2, 1]. The second largest element is 5, which is at index 1.
Output: 5
2. Min-Heap approach:
o Min-heap after inserting the first k=2 elements: [3, 2]
o After processing the next elements:
For 1, no change since it's smaller than 3.
For 5, replace 3 with 5. Min-heap is [5, 2].
For 6, replace 2 with 6. Min-heap is [5, 6].
For 4, no change since it's smaller than 5.
o The root of the heap is 5.