215. Kth Largest Element in an Array(返回数组中第几大元素)(leetcode)

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.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

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

题目描述:找到第 k 大的元素。

方法一:快排

1、快排思想:通过第一遍排序将待排记录分隔成两部分,然后将两部分分别排序。

分割部分思想:两个指针:一个从前向后L1,一个从后向前L2。L1找比它大的。L2找比它小的。

在没相遇前找到了就交换。如果相遇就降L2指的数与标准值交换。

算法复杂度:o(nlogn

时间复杂度 O(N)              空间复杂度 O(1)

方式二:堆排序

1、堆排序分为

  大顶堆:堆顶记录的是最大关键字

  小顶堆:堆顶记录的是最小关键字

2、本题利用的是建立堆的思想。

3、时间复杂度:o(NlogN)

时间复杂度 O(NlogK)              空间复杂度 O(K)

方法三:利用Arrays.sort(nums)函数

苟有恒,何必三更眠五更起;最无益,莫过一日暴十日寒。
原文地址:https://www.cnblogs.com/shaer/p/10424065.html