整数无序数组求第k大数

题目来自牛客网
https://www.nowcoder.com/practice/097ab63cffa847d89716f2ca8c23524f?tpId=90&tqId=30914&tPage=7&rp=7&ru=/ta/2018test&qru=/ta/2018test/question-ranking
在这里插入图片描述
两种方法,方法一:使用快排,经过一轮之后,元素temp被放到中间,前面的小于等于它,后面的大于等于它,如果元素temp的位置是i(从0开始),那么temp为第i+1小的数,本题求第k大的数,所以i=len-k(在代码中对应int k = len - scanner.nextInt();),len为数组中元素个数。如果temp的位置小于i,那么,往后找,如果大于i,往前找,相等,temp即为所求。
方法二:求第k大数,使用小顶堆,堆中有k个元素,堆顶元素为当前的第k大数,如果堆中不足k个元素,直接入堆,否则,如果大于堆顶,删除堆顶,这个数入堆。最后,堆顶元素即为所求。
代码如下:

import java.util.*;

public class Solution139 {
    //使用小顶堆
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		String[] strs = scanner.nextLine().split(" ");
		int len = strs.length;
		int[] num = new int[len];
		for (int i = 0; i < len; i++) {
			num[i] = Integer.parseInt(strs[i]);
		}
		int k = scanner.nextInt();
		scanner.close();
		//PriorityQueue是用堆实现的,默认就是小顶堆
		PriorityQueue<Integer> queue = new PriorityQueue<>(k);
		for (int i = 0; i < len; i++) {
			if (queue.size() < k) {
				queue.offer(num[i]);
			} else if (num[i] > queue.peek()) {
				queue.poll();
				queue.offer(num[i]);
			}
		}
		System.out.println(queue.peek());

	}

    //使用快排的思想
	public static void main2(String[] args) {

		Scanner scanner = new Scanner(System.in);
		String[] strs = scanner.nextLine().split(" ");
		int len = strs.length;
		int[] num = new int[len];
		for (int i = 0; i < len; i++) {
			num[i] = Integer.parseInt(strs[i]);
		}
		int k = len - scanner.nextInt();
		scanner.close();

		int begin = 0;
		int end = len - 1;
		int index = aTurnQuickSort(num, begin, end);
		while (index != k) {
			if (index < k) {
				begin = index + 1;
				index = aTurnQuickSort(num, begin, end);
			} else {
				end = index - 1;
				index = aTurnQuickSort(num, begin, end);
			}
		}
		System.out.println(num[index]);

	}

	public static int aTurnQuickSort(int[] num, int begin, int end) {
		int i = begin;
		int j = end;
		int temp = num[i];
		while (i < j) {
			while (i < j && num[j] >= temp) {
				j--;
			}
			num[i] = num[j];
			while (i < j && num[i] <= temp) {
				i++;
			}
			num[j] = num[i];
		}
		num[i] = temp;
		return i;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值