[leetcode]215. Kth Largest Element in an Array
来源:互联网 发布:淘宝店铺提高销量 编辑:程序博客网 时间:2024/06/05 11:28
divide and conquer
题目:
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的值放在左边,小于关键点pivot的值放在右边。如果关键点恰好是nums[k-1],那么该关键点就是数组的第k大的数。如果关键点
class Solution {public: int findKthLargest(vector<int>& nums, int k) { int left = 0; int right = nums.size()-1; while (true) { int pos = getPosition(nums, left, right); if (pos == k-1) return nums[k-1]; if (pos > k-1) right = pos-1; else left = pos+1; } } int getPosition(vector<int> &nums, int left, int right) { int pivot = nums[left]; int l = left+1, r = right; while (l <= r) { if (nums[l] < pivot && nums[r] > pivot) { swap(nums[l], nums[r]); } if (nums[l] >= pivot) l++; if (nums[r] <= pivot) r--; } swap(pivot, nums[r]); return r; }};
优先队列:
优先队列可以从大到小自动排列,所以将前k-1个数据弹出,队头就是第k大数据。
class Solution {public: int findKthLargest(vector<int>& nums, int k) { sort(nums.begin(), nums.end()); return nums[nums.size() - k]; }};
阅读全文
0 0
- Leetcode Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- [LeetCode] Kth Largest Element in an Array
- [leetcode] Kth Largest Element in an Array
- leetcode--Kth Largest Element in an Array
- #leetcode#Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- 【Leetcode】Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- Kth Largest Element in an Array -- leetcode
- [Leetcode]Kth Largest Element in an Array
- [LeetCode]Kth Largest Element in an Array
- *LeetCode-Kth Largest Element in an Array
- LeetCode----Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- leetcode-Kth Largest Element in an Array
- LeetCode -- Kth Largest Element in an Array
- 过滤器-禁止未授权的IP访问站点
- 记一次samba的配置经历
- 简单粗暴地理解 JavaScript 原型链
- 62. Unique Paths & 63. Unique Paths II(唯一路径1&2)
- MarkDown 高级操作
- [leetcode]215. Kth Largest Element in an Array
- mysql 字符集utf8设置 ,中文乱码mysql设置
- 基于docker的ceph集群
- LeetCode 104 Maximum Depth of Binary Tree
- 开发了一个手机版的书讯网站
- Unity3D-初识Unity
- 心算小程序
- 带阻滤波器对周期性噪声消除matlab实现
- 淘淘商城的架构分析