作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/kth-largest-element-in-an-array/description/

题目描述

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大的值。

解题方法

方法一:移除最大值

找出第k大的数字。这个题可以直接排序,速度还挺快。我的做法是通过循环k-1次,每次都在列表中去除列表的最大值。注意,列表的remove每次只会移除一个值。例如:

In [1]: a = [1,2,3,3,3,3]

In [2]: a.remove(3)

In [3]: a
Out[3]: [1, 2, 3, 3, 3] In [4]: a.remove(3) In [5]: a
Out[5]: [1, 2, 3, 3]

这题答案:

class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
for i in range(k - 1):
nums.remove(max(nums))
return max(nums)

方法二:排序

排序之后直接找倒数第k个数字即可。

class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
return nums[nums.size() - k];
}
};

方法三:大顶堆

使用大顶堆,弹出k-1个数字,那么再弹一次就是第k大的值了。

class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int> q;
for (int n : nums) {
q.push(n);
}
int res = 0;
while (k--) {
res = q.top(); q.pop();
}
return res;
}
};

方法四:partition

待完成。

日期

2018 年 2 月 5 日
2018 年 12 月 23 日 —— 周赛成绩新高

最新文章

  1. jquery1.7.2的源码分析(二)
  2. Db2数据库的备份和恢复
  3. PHP面向对象基础part.1
  4. iOS-GCD多线程
  5. MongoDB 复制集 (一) 成员介绍
  6. spring mvc 使用jsr-303进行表单验证的方法介绍
  7. php抽象类和接口
  8. android UI进阶之弹窗的使用(2)--实现通讯录的弹窗效果
  9. Xamarin开发笔记—设备类&amp;第三方弹窗的使用和注意事项
  10. 面向对象编程笔记--static
  11. Fastify 系列教程一(路由和日志)
  12. BZOJ2339[HNOI2011]卡农——递推+组合数
  13. 下载caffe慢
  14. [Codeforces771E]Bear and Rectangle Strips
  15. bzoj2152: 聪聪可可 点分治
  16. vue cli 配置信息说明
  17. 初试PyOpenGL四 (Python+OpenGL)GPU粒子系统与基本碰撞
  18. Centos7.2安装tomcat+Myeclipse(遇到的一些问题与总结)+web项目实战
  19. sql中where以后and和or的用法
  20. Delphi APP 開發入門(九)拍照與分享

热门文章

  1. rust Option枚举
  2. 动态生成多个选择项【c#】
  3. 【php安全】 register_argc_argv 造成的漏洞分析
  4. 【leetcode】15.&#160;3 Sum 双指针 压缩搜索空间
  5. Oracle中dbms_random包详解
  6. Linux基础命令---mysqldump数据库备份
  7. spring jdbc 配置数据源连接数据库
  8. SpringBoot(1):初始SpringBoot
  9. Linux 性能优化笔记:应用监控
  10. 用graphviz可视化决策树