您的位置:首页 > 编程语言 > Java开发

leetcode 215. Kth Largest Element in an Array | Java最短代码实现

2016-03-10 15:31 651 查看
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.

欢迎优化!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: