leetcode 215. Kth Largest Element in an Array

本文介绍了一种使用最小堆及快速选择算法解决寻找未排序数组中第K大元素的方法。通过实例展示了如何利用这两种方法有效地找到目标元素。

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

Note: 
You may assume k is always valid, 1 ? k ? array's length.

又是一道很经典的问题。

我用的最小堆做的。

public int findKthLargest(int[] nums, int k) {
	PriorityQueue<Integer> queue=new PriorityQueue<Integer>();
	for(int i=0;i<nums.length;i++){
		if(queue.size()<k){
			queue.offer(nums[i]);
		}
		else{
			int kLargest=queue.peek();
			if(kLargest<nums[i]){
				queue.poll();
				queue.offer(nums[i]);
			}
		}
	}
	return queue.peek();
}
大神表示:这道题可以用quickSelect算法(类似于quicksort中的划分方法),时间复杂度是O(n)。

把 numbers < pivot 放到 pivot 的左侧
把 numbers > pivot 放到 pivot 的右侧

接着令 k=nums.length-k ( 第 k 大的数 ,是第 nums.length-k 索引小的数)
如 [3,2,1,5,6,4] ,第2大的数是5,把小于等于5的数放到左边后,[3,2,1,4,5,6],5的索引是4,符合6-2=4

//如[1,2,3],第二大的数为2,将比2小的数放到2左边后,对应索引为index=3-2=1
if indexOfPivot == k, return A[k]   
else if indexOfPivot < k, keep checking right part to pivot
else if indexOfPivot > k, keep checking left part to pivot

Time complexity = O(n)

每次抛弃一半数组: n+(n/2)+(n/4)..1 = n + (n-1) = O(2n-1) = O(n), because n/2+n/4+n/8+..1=n-1.

Quick Select Solution Code:

public int findKthLargest(int[] nums, int k) {
	if (nums == null || nums.length == 0) return Integer.MAX_VALUE;
    return findKthLargest(nums, 0, nums.length - 1, nums.length - k);
}    

public int findKthLargest(int[] nums, int left, int right, int k) {// quick select: kth smallest
	if (left > right) return Integer.MAX_VALUE;
	
	int pivot = nums[right];// Take A[right] as the pivot, 
	int low = left;
	for (int i = left; i < right; i++) {
	        //把 所有小于等于pivot的数都集中到最左边
		if (nums[i] <= pivot){ // Put numbers < pivot to pivot's left
			swap(nums, low, i);			
			low++;
	        }		
	}
	swap(nums, low, right);// Finally, swap A[right] with A[low]
	
	if (low == k)// Found kth smallest number
		return nums[low];
	else if (low < k)// Check right part
		return findKthLargest(nums, low + 1, right, k);
	else // Check left part
		return findKthLargest(nums, left, low - 1, k);
} 

void swap(int[] A, int i, int j) {
	int tmp = A[i];
	A[i] = A[j];
	A[j] = tmp;				
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值