zoukankan      html  css  js  c++  java
  • 最小的k个数1 堆排序实现

    // 使用堆排序实现 其时间复杂度为O(nlgn)
        private static void buildMaxHeap(int[] input, int end)
        {
            // 从非叶子节点开始进行
            for (int i = (end - 1) / 2; i >= 0; i--)
            {
                // 当前节点 cur的字节点位cur*2+1&cur*2+2
                int cur = i;
                // cur的右孩子存在
                while (cur * 2 + 1 < end)
                {
                    int bigIndex = cur * 2 + 1;
                    int rightOfCur = cur * 2 + 2;
                    // 找出孩子节点中的最大值索引
                    if (input[bigIndex] < input[rightOfCur])
                    {
                        bigIndex++;
                    }
                    // input[cur]节点与input[bigIndex] 进行比较进
                    if (input[cur] < input[bigIndex])
                    {
                        int temp = input[cur];
                        input[cur] = input[bigIndex];
                        input[bigIndex] = temp;
                        // 尤其重要
                        cur = bigIndex;
                    }
                    else
                    {
                        break;
                    }

                }
            }
        }

        private static int[] minKOfNums(int[] nums, int k)
        {
            // 特殊值考虑
            if (nums == null || nums.length < k || k <= 0)
            {
                return null;
            }
            // 声明堆
            int[] maxHeap = new int[k];
            // 初始化
            for (int i = 0; i < k; i++)
            {
                maxHeap[i] = nums[i];
            }
            // 建成最大堆
            buildMaxHeap(maxHeap, maxHeap.length - 1);
            // 进行后续的比较
            for (int i = k; i < nums.length; i++)
            {
                if (maxHeap[0] > nums[i])
                {
                    maxHeap[0] = nums[i];
                    // 重新建maxHeap
                    buildMaxHeap(maxHeap, maxHeap.length - 1);
                }
            }
            return maxHeap;
        }

  • 相关阅读:
    CodeForces 7B
    CodeForces 4D
    离散化
    线段树入门
    洛谷 P3951 小凯的疑惑(赛瓦维斯特定理)
    Codeforces 1295D Same GCDs (欧拉函数)
    Codeforces 1295C Obtain The String (二分)
    Codeforces 1295B Infinite Prefixes
    Codeforces 1295A Display The Number(思维)
    Codeforces 1294F Three Paths on a Tree(树的直径,思维)
  • 原文地址:https://www.cnblogs.com/qingtianBKY/p/8283168.html
Copyright © 2011-2022 走看看