一.题目描述
给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素。
请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
示例 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
提示:
1 <= k <= nums.length <= 104
-104 <= nums[i] <= 104
二.题目解析
1.暴力法
public int findKthLargest(int[] nums, int k) {
/*暴力法 排序
时间复杂度O(nlogn),空间复杂度O(1)
* */
if(nums == null || nums.length == 0 || k > nums.length){
return -1;
}
Arrays.sort(nums);
return nums[nums.length - k];//如第1个大的元素在数组中下标是nums.length-1
}
2.快速排序法
class Solution {
public int findKthLargest(int[] nums, int k) {
/*快速排序(双指针+分治法)-从大到小排序
时间复杂度O(n),空间复杂度O(logn)用到栈
* */
if(nums == null || nums.length == 0 || k > nums.length){
return -1;
}
//递归过程中第K大可能会变化,但是下标不会变化,故传入K-1用下标判断
return quickSort(nums,0,nums.length - 1,k - 1);
}
private int quickSort(int[] nums, int low, int high, int index) {
//只有一个元素的情况
if(low == high && low == index){
return nums[low];
}
//产生随机基准数,降低递归树加深的可能性,最糟糕的情况是顺序数组与倒序数组
int privot = low + (int)(Math.random()*(high - low + 1));
swap(nums, low, privot);
if(low < high){
//获取基准元素的最终位置
int middle = getMiddle(nums,low,high);
//如果这个基准元素位置就是我们想要的位置就返回
if(middle == index){
return nums[middle];
}
if(middle > index){
return quickSort(nums,low,middle - 1,index);
}else{
return quickSort(nums,middle + 1,high,index);
}
}
return -1;
}
private int getMiddle(int[] nums, int low, int high) {
/*获取基准元素的最终位置*/
int temp = nums[low];
while(low < high){
while (low < high && nums[high] < temp){
high--;
}
//一定要加if判断,因为high--后可能不能满足low < high
if(low < high) {
nums[low++] = nums[high];
}
while (low < high && nums[low] >= temp){
low++;
}
//一定要加if判断,理由同上,满足low<high才交换
if(low < high) {
nums[high--] = nums[low];
}
}
//low是基准元素最终的位置,
//在之前遍历的过程中,无论怎么交换,
//都满足low所经历的都是>=privot,high经历的都是<privot
nums[low] = temp;
return low;
}
private void swap(int[] nums, int low, int privot) {
int temp = nums[low];
nums[low] = nums[privot];
nums[privot] = temp;
}
}
附快速排序代码(顺序排序从小到大):
public void quick(int[] nums) throws Exception {
if(nums == null || nums.length == 0){
throw new Exception("传入参数非法");
}
quickSort(nums,0,nums.length - 1);
}
private void quickSort(int[] nums, int low, int high) {
//产生随机基准数,降低递归树加深的可能性,最糟糕的情况是顺序数组与倒序数组
int privot = low + (int)(Math.random()*(high - low + 1));
swap(nums, low, privot);
if(low < high){
//获取基准元素的最终位置
int middle = getMiddle(nums,low,high);
quickSort(nums,low,middle - 1);
quickSort(nums,middle + 1,high);
}
}
private int getMiddle(int[] nums, int low, int high) {
/*获取基准元素的最终位置*/
int temp = nums[low];
while(low < high){
while (low < high && nums[high] > temp){
high--;
}
//一定要加if判断,因为high--后可能不能满足low < high
if(low < high) {
nums[low++] = nums[high];
}
while (low < high && nums[low] <= temp){
low++;
}
//一定要加if判断,理由同上,满足low<high才交换
if(low < high) {
nums[high--] = nums[low];
}
}
//low是基准元素最终的位置,
//在之前遍历的过程中,无论怎么交换,
//都满足low所经历的都是<=privot,high经历的都是>privot
nums[low] = temp;
return low;
}
private void swap(int[] nums, int low, int privot) {
int temp = nums[low];
nums[low] = nums[privot];
nums[privot] = temp;
}