LeetCode——Kth Largest Element in an Array
生活随笔
收集整理的這篇文章主要介紹了
LeetCode——Kth Largest Element in an Array
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
LeetCode——Kth Largest Element in an Array
Question
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.
解題思路
http://www.cnblogs.com/zhonghuasong/p/6553931.html
具體實現
#include <iostream> #include <vector>using namespace std;class Solution { public:int findKthLargest(vector<int>& nums, int k) {// 建立節點個數為k的堆,直接用前k個節點// 然后遍歷剩下的節點,如果比堆的頂點都小的直接舍棄,大的則將堆的頂點用新的節點替換,然后再進行堆的調整// 所以時間復雜度為 O(nlgk)// 建立大小為k的堆for (int i = 0; i < k; i++) {MinHeapFixup(nums, i);}for (int i = k; i < nums.size(); i++) {if (nums[i] > nums[0]) {nums[0] = nums[i];MinHeapFixdown(nums, 0, k);}}return nums[0];}// 堆的插入void MinHeapFixup(vector<int>& nums, int i) {int j, tmp;tmp = nums[i];j = (i - 1) / 2; //父節點while(j >= 0 && i != 0) {if (nums[j] < tmp)break;nums[i] = nums[j];i = j;j = (i - 1) / 2;}nums[i] = tmp;}// 堆的刪除(堆的調整,從根部開始)// 堆刪除的實際做法,就是將數組中的最后一個節點和根節點對換,刪除最后一個元素,然后再把堆進行調整。void MinHeapFixdown(vector<int>&nums, int i, int k) {int j, tmp;tmp = nums[i];j = 2 * i + 1; // 孩子節點while (j < k) {if (j + 1 < k && nums[j + 1] < nums[j]) //在左右孩子中找最小的孩子j++;if (nums[j] > tmp)break;nums[i] = nums[j];i = j;j = 2 * i + 1;}nums[i] = tmp;} };int main() {Solution* solution = new Solution();int arr[] = {3, 1, 2, 4};vector<int> vec(arr, arr + 4);cout << solution->findKthLargest(vec, 2) << endl;return 0; }轉載于:https://www.cnblogs.com/zhonghuasong/p/6554037.html
總結
以上是生活随笔為你收集整理的LeetCode——Kth Largest Element in an Array的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 页面刷新
- 下一篇: yum 的 group的信息