zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    TF.VARIABLE、TF.GET_VARIABLE、TF.VARIABLE_SCOPE以及TF.NAME_SCOPE关系
    人工智能、机器学习、深度学习、神经网络概念说明
    神经网络
    人工智能学习资料汇总
    tf.nn.conv2d。卷积函数
    卷积神经网络(CNN)
    Softmax函数模型介绍
    使用virtualenv进行python环境隔离
    升级mac自带的python
    MAC资料汇总
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/6554037.html
Copyright © 2011-2022 走看看