Total Accepted: 46230 Total
Submissions: 143069 Difficulty: Medium
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
【抛砖】
该实现是按照快排的思想进行实现,时间复杂度为O(n*logn):
public int findKthLargest(int[] nums, int k) {
int leftBoundary = 0;
int rightBouondary = nums.length - 1;
while (leftBoundary < rightBouondary) {
int temp = nums[leftBoundary];
int left = leftBoundary;
int right = rightBouondary;
while (left < right) {
while (right > left && nums[right] <= temp)
right--;
nums[left] = nums[right];
while (left < right && nums[left] > temp)
left++;
nums[right] = nums[left];
}
nums[left] = temp;
if (left == k - 1) return nums[left];
else if (left < k - 1) leftBoundary = left + 1;
else rightBouondary = left - 1;
}
return nums[leftBoundary];
}31 / 31 test
cases passed. Runtime: 55
ms Your runtime beats 27.71% of javasubmissions.欢迎优化!
本文介绍了一种使用快速排序思想的算法来找到未排序数组中第K大的元素,时间复杂度为O(n*logn)。通过实例演示算法实现,并提供了测试用例和运行结果。
887

被折叠的 条评论
为什么被折叠?



