求第K大元素-Java-数组中数据可重复
1、题目描述
一个非空大的整数数组,至少有3个元素,可正可负;
求第三大的元素,
测试用例:
[6,5,4,4,1,2]
输出:4
2、解决方法一:大小为k的小根堆
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main1 {
/**
* @param args
* 【查找第k大的元素】,数组有重复数字出现 ,数字可正可负
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
String s = in.nextLine().trim();
String strs[] = s.substring(1, s.length() - 1).split(",");
int nums[] = new int[strs.length];
for (int i = 0; i < strs.length; i++) {
nums[i] = Integer.parseInt(strs[i]);
}
// 使用size为3的小根堆实现
System.out.println(findKthLargest(nums, 3));
}
public static int findKthLargest(int[] nums, int k) {
// 大小为k的小根堆,比根大的数都可进入小根堆,小根堆大小最大不超过3
// 遍历完毕,则根节点即为所求
PriorityQueue<Integer> q = new PriorityQueue<Integer>(k);
for (int i : nums) {
q.offer(i);
if (q.size() > k) {
q.poll();
}
}
return q.peek();
}
}
3、解决方法二:快速排序+优化比较,找到就可返回结果并退出
import java.util.Scanner;
public class Main2 {
/**
* @param args
* 【查找第k大的元素】,数组有重复数字出现 ,数字可正可负
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
String strs[] = in.nextLine().trim().split(",");
int nums[] = new int[strs.length];
for (int i = 0; i < strs.length; i++) {
nums[i] = Integer.parseInt(strs[i]);
}
System.out.println(findKthLargest(nums, 2));
}
public static int findKthLargest(int[] nums, int k) {
if (k < 1 || nums == null) {
return 0;
}
return getKth(nums.length - k + 1, nums, 0, nums.length - 1);
}
public static int getKth(int k, int[] nums, int start, int end) {
int pivot = nums[end];
int left = start;
int right = end;
while (true) {
while (nums[left] < pivot && left < right) {
left++;
}
while (nums[right] >= pivot && right > left) {
right--;
}
if (left == right) {
break;
}
swap(nums, left, right);
}
swap(nums, left, end);
if (k == left + 1) {
return pivot;
} else if (k < left + 1) {
return getKth(k, nums, start, left - 1);
} else {
return getKth(k, nums, left + 1, end);
}
}
public static void swap(int[] nums, int n1, int n2) {
int tmp = nums[n1];
nums[n1] = nums[n2];
nums[n2] = tmp;
}
}
参考链接;
https://blog.csdn.net/hzh_csdn/article/details/53446211