LeetCode OJ 215. Kth Largest Element in an Array 堆排序求解

    题目链接:https://leetcode.com/problems/kth-largest-element-in-an-array/

215. Kth Largest Element in an Array

My Submissions
Total Accepted: 43442  Total Submissions: 136063  Difficulty: Medium

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.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss


    求给定数组的第K大的元素。如果先排序,然后取第K个元素,那么时间复杂度是O(n*log n)。借助堆的数据结构,可以把时间复杂度降到O(n*logk)。

    如果求第K大的元素,那么要构建的是小顶堆。求第K小的元素,那么要构建大顶堆!先构建k个元素的堆,另外i-k个元素逐个跟堆顶元素比较,如果比堆顶元素小,那么就将该元素纳入堆中,并保持堆的性质。

    我的AC代码

public class KthLargestElementinanArray {

	public static void main(String[] args) {
		int[] a = { 3, 2, 1, 5, 6, 4 };
		System.out.println(findKthLargest(a, 1));
		int[] b = { -1,2,0};
		System.out.println(findKthLargest(b, 3));
		int[] c = { 3,1,2,4};
		System.out.println(findKthLargest(c, 2));

	}

	public static int findKthLargest(int[] nums, int k) {
		int[] heap = new int[k];

		heap[0] = nums[0];
		for (int i = 1; i < k; i++) {
			siftUp(nums[i], heap, i);
		}

		for (int i = k; i < nums.length; i++) {
			siftDown(nums, k, heap, i);
		}

		return heap[0];
	}

	private static void siftDown(int[] nums, int k, int[] heap, int i) {
		if (nums[i] > heap[0]) {
			heap[0] = nums[i];
			int p = 0;
			while(p < k) {
				int minChild = 2 * p + 1;
				if(minChild + 1 < k && heap[minChild] > heap[minChild + 1]) minChild ++;
				if(minChild < k && heap[p] > heap[minChild]) {
					swap(heap, p, minChild);
					p = minChild;
				} else break;
			}
		}
	}

	private static void siftUp(int num, int[] heap, int i) {
		int p = i;
		heap[i] = num;
		while (p != 0) {
			int parent = (p - 1) / 2;
			if (heap[parent] > heap[p]) {
				swap(heap, p, parent);
			}
			p = parent;
		}
	}

	private static void swap(int[] heap, int p, int parent) {
		int temp = heap[parent];
		heap[parent] = heap[p];
		heap[p] = temp;
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值