leetcode之 Kth Largest Element in an Array
来源:互联网 发布:流程优化的人员要求 编辑:程序博客网 时间:2024/06/05 04:01
题目:
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.
解答:
注意题目中写的是第k大不是第k小
思想很简答,就是利用快速排序的思想来实现,之前在算法设计分析上学习过, 总体复杂度是O(n)的(但是忘记怎么算出这个复杂度的了,想要看的可以看书)
同时还注意到C++中已经有了直接找到第n个数的函数,nth_element(),想要知道用法的可以自己问度娘
class Solution {public: void swap(int i,int j, vector<int>& nums) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } int kth(vector<int>& nums, int i, int j, int k) { while(true) { int pos1 = i, pos2 = i; int tag = nums[j]; while(pos2 < j) { if(nums[pos2] < tag) { swap(pos1,pos2,nums); pos1++; pos2++; } else pos2++; } if(pos1 - i + 1 == k) return tag; if(pos1 - i + 1 > k) { j = pos1 - 1; } if(pos1 - i + 1 < k) { i = pos1; j = j - 1; k = k - pos1 - 1 + i; } } } int findKthLargest(vector<int>& nums, int k) { return kth(nums, 0, nums.size() - 1, nums.size() - k + 1); }};
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
- oracle 检测坏块的方法
- Android 资源文件中@、@android:type、@*、?、@+含义和区别
- 支票面额 PAT
- json字符串的封装(jackson框架)
- x_algor.c 分析
- leetcode之 Kth Largest Element in an Array
- c++反汇编与逆向分析--小结
- Mybatis的MapperRegistry错误
- 七牛云音视频新功能:音频支持AAC_HE
- x264命令行参数解释
- 让Android Support V4中的SwipeRefreshLayout支持上拉加载更多
- 示例代码
- android 单价乘以数量计算总价 乘法
- Sublime Text3常用快捷键