描述
在数组中找到第 k 大的元素。
你可以交换数组中的元素的位置
样例
样例 1:
输入:
n = 1, nums = [1,3,4,2]
输出:
4
样例 2:
输入:
n = 3, nums = [9,3,2,4,8]
输出:
4
挑战
要求时间复杂度为O(n),空间复杂度为O(1)。
可以使用快排/堆排等等,这里我使用选择排序。
public class Exp5 {
public static int findMax(int n, int[] nums){
// write your code here
int result = nums[0];
for (int i = 0; i < nums.length; i++) {
int max = nums[i];
int max_index = i;
for (int j = i; j < nums.length; j++) {
if (max < nums[j]) {
max = nums[j];
max_index = j;
}
}
int temp = nums[i];
nums[i] = nums[max_index];
nums[max_index] = temp;
if (i== n-1) {
result = nums[i];
break;
}
}
return result;
}
public static int findMin(int n, int[] nums){
// write your code here
int result = nums[0];
for (int i = 0; i < nums.length; i++) {
int min = nums[i];
int min_index = i;
for (int j = i; j < nums.length; j++) {
if (min > nums[j]) {
min = nums[j];
min_index = j;
}
}
int temp = nums[i];
nums[i] = nums[min_index];
nums[min_index] = temp;
if (i== nums.length-n) {
result = nums[i];
break;
}
}
return result;
}
public static int kthLargestElement(int n, int[] nums) {
// write your code here
int result = 0;
if(n>nums.length/2){
result = findMin(n,nums);
}else{
result = findMax(n,nums);
}
return result;
}
public static void main(String[] args) {
int n = 105;
//int nums[] = {1,3,4,2};
int nums[] = {595240, 373125, 463748, 417209, 209393, 747977, 864346, 419023, 925673, 307640, 597868, 833339, 130763, 814627, 766415, 79576, 459038, 990103, 944521, 708820, 473246, 499960, 742286, 758503, 270229, 991199, 770718, 529265, 498975, 721068, 727348, 29619, 712557, 724373, 823743, 318203, 290432, 476213, 412181, 869308, 496482, 793858, 676162, 165869, 160511, 260864, 502521, 611678, 786798, 356560, 916620, 922168, 89350, 857183, 964051, 979979, 916565, 186532, 905289, 653307, 351329, 195491, 866281, 183964, 650765, 675046, 661642, 578936, 78684, 50105, 688326, 648786, 645823, 652329, 961553, 381367, 506439, 77735, 707959, 373271, 316194, 185079, 686945, 342608, 980794, 78777, 687520, 27772, 711098, 661265, 167824, 688245, 286419, 400823, 198119, 35400, 916784, 81169, 874377, 377128, 922531, 866135, 319912, 867697, 10904};
//595240
//10904
System.out.println(kthLargestElement(n, nums));
}
}