第k大的元素
程序员文章站
2024-03-16 08:30:46
...
析:借助快速排序的思想
import java.util.Scanner;
public class Main4 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String numStr=sc.nextLine();
String[] nums = numStr.split(" ");
int[] arr = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
arr[i]= Integer.valueOf(nums[i]);
}
int k=sc.nextInt();
System.out.println(kthLargestElement(k,arr));
}
public static int kthLargestElement(int k, int[] nums) {
if(null == nums ||k <= 0 || nums.length < k) return Integer.MIN_VALUE;
kthMax(nums, 0, nums.length-1, k);
return nums[k-1];
}
// 快速排序的近似写法
public static void kthMax(int[] nums, int left, int right, int k) {
int mid = partition(nums, left, right);
if(mid == k-1) return;
if(mid > k-1)
kthMax(nums, left, mid-1, k);
else
kthMax(nums, mid+1, right, k);
}
public static int partition(int[] nums, int left, int right) {
int temp = nums[left];
while(left < right) {
while(left < right && nums[right] <= temp)
right--;
nums[left] = nums[right];
while(left < right && nums[left] > temp)
left++;
nums[right] = nums[left];
}
nums[left] = temp;
return left;
}
}