215. Kth Largest Element in an Array
- Total Accepted: 114574
- Total Submissions: 300733
- Difficulty: Medium
- Contributors: Admin
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.
题解:
仿照快速排序的方法,取最后一个数的下标为pivot,将其余的数字分成大于最后一个数和小于最后一个数。首先判断第pivot个数是不是就是第k大的数,是则直接返回,不是就判断是处于大于最后一个数的那部分还是小于最后一个数的那部分,再对选出来的那一部分递归调用这个函数。代码如下:
提交之后显示通过了测试但内存超过限制,具体原因不明。