[LeetCode] Kth Largest Element in an Array
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.
这道没啥可说的。最容易想到的办法就是不管大小先把整个数列sorting,然后直接return第(数列.length-k)个数即可。但是整个如果数列很长的话就比较浪费时间啦。代码很简单。如下。
public class Solution {
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length-k];
}
}
但是啦,个人觉得其实最快的应该是用quick select来做。当然了代码就比sorting要略麻烦一些。
qucike select是直接用前后开始找,就不管这个数列多长,速度都不会有太大影响。
public class Solution {
public int findKthLargest(int[] nums, int k) {
int start = 0, end = nums.length - 1, index = nums.length - k;
while (start < end) {
int pivot = getKth(nums, start, end);
if (pivot < index) {
start = pivot + 1;
}else if (pivot > index) {
end = pivot - 1;
}else{
return nums[pivot];
}
}
return nums[start];
}
private int getKth(int[] nums, int start, int end) {
int pivot = start, temp;
while (start <= end) {
while (start <= end && nums[start] <= nums[pivot]) {
start++;
}
while (start <= end && nums[end] > nums[pivot]){
end--;
}
if (start > end) {
break;
}
temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
}
temp = nums[end];
nums[end] = nums[pivot];
nums[pivot] = temp;
return end;
}
}
浙公网安备 33010602011771号