[LintCode] 第K大元素 Kth Largest Element
来源:互联网 发布:sqlserver高效分页 编辑:程序博客网 时间:2024/04/30 04:35
在数组中找到第k大的元素。
样例
给出数组 [9,3,2,4,8],第三大的元素是 4
给出数组 [1,2,3,4,5],第一大的元素是 5,第二大的元素是 4,第三大的元素是 3,以此类推
挑战
要求时间复杂度为O(n),空间复杂度为O(1)
Find K-th largest element in an array.
Example
In array [9,3,2,4,8], the 3rd largest element is 4.
In array [1,2,3,4,5], the 1st largest element is 5, 2nd largest element is 4, 3rd largest element is 3 and etc.
Challenge
O(n) time, O(1) extra memory.
时间复杂度O(nlogn)?
class Solution { /* * @param k : description of k * @param nums : array of nums * @return: description of return */ public int kthLargestElement(int k, int[] nums) { if(null == nums ||k <= 0 || nums.length < k) return Integer.MIN_VALUE; kthMax(nums, 0, nums.length-1, k); return nums[k-1]; } public void kthMax(int[] nums, int left, int right, int k) { int mid = partition(nums, left, right); if(mid == k-1) return; if(mid > k-1) kthMax(nums, left, mid-1, k); else kthMax(nums, mid+1, right, k); } public int partition(int[] nums, int left, int right) { int temp = nums[left]; while(left < right) { while(left < right && nums[right] <= temp) right--; nums[left] = nums[right]; while(left < right && nums[left] > temp) left++; nums[right] = nums[left]; } nums[left] = temp; return left; }};
0 0
- [LintCode] 第K大元素 Kth Largest Element
- LeetCode OJ 之 Kth Largest Element in an Array(数组中的第k大元素)
- The kth largest element in max-heap 最大堆的第k大元素
- Leetcode 215 Kth Largest Element in an Array 数组中第k大的元素
- leetcode215---Kth Largest Element in an Array(第k大元素)
- LeetCode 215. Kth Largest Element in an Array(第K大元素)
- [LeetCode] Kth Largest Element in an Array (找出数组的第k大的元素)
- 5.Kth Largest Element-第k大元素(中等题)
- Kth Largest Element in an Array(数组中第K大元素)
- 【LeetCode】215. Kth Largest Element in an Array找第K大的元素
- 215. Kth Largest Element in an Array(数组中第k大元素)
- Lintcode - kth largest element
- **[Lintcode]Kth Largest Element
- LintCode 5: Kth Largest Element
- Kth Largest Element in an Array 数组中的第K大的数
- 数组-Kth Largest Element in an Array(找出第K大的数)
- LeetCode 二分查找第K大的数215. Kth Largest Element in an Array
- 215. Kth Largest Element in an Array(数组中第k大的数字)
- absolute绝对定位的深入解读
- mac pod 的使用总结
- Exercise(6):八皇后
- 三角公式 - 记忆版
- CSS3中盒模型的新增属性overflow
- [LintCode] 第K大元素 Kth Largest Element
- 从CMO到龙泉寺弟子:佛法改变人生
- AYITACM2016省赛第二周 G - History Grading历史评分(最长公共子序列)
- 转载大神文章:前端变化
- 病毒,入侵和网络攻击(摘抄)
- pthread 条件变量(cond),sem,mutex
- css设计注意事项
- Java学习eclipse生成jar包
- [工作点滴]新建分支 git 命令