当前位置:网站首页>The k-th element in the array [heap row + actual time complexity of heap building]
The k-th element in the array [heap row + actual time complexity of heap building]
2022-06-28 15:22:00 【REN_ Linsen】
Stack row + Time complexity of reactor building
Preface
The heap can be arranged without complete sorting , Take second place K Big element , But the same is true of selective sorting .
So who will run faster ? When building a reactor , Need to adjust n/2 Time , The maximum depth of each time is log2(n), The first visual impression is to build a pile T(n) = O(nlgon), It's not .
Heap discharge k The time of the big element = Build time + take k The time of the first element = (O(n) - O(log2n) - 1) + O(klog2n) = O(n);
Select sort to get k The time of the big element = O(kn) = O(n).
because (O(n) - O(log2n) - 1) + O(klog2n) <O(kn), So stack faster .
The proof is in the comments before the second part of the code .
One 、 The... In the array K Big element

Two 、 Proof of reactor building complexity
prove : Take the full binary tree with the most nodes as an example , Tree height is h,
Set the current layer as k, Then this layer has 2^(k - 1)^ Nodes , Each node needs to be adjusted h - k The depth of the .
therefore ,T(n) = 20 * (h - 1) + 21 * (h - 2) +…+2^(h - 2) * 1, Obviously, it is a typical difference ratio sequence , Just offset and subtract .
2T(n) = 21 * (h - 1) + 22 * (h - 2) +…+2^(h - 2)^ * 2 + 2^(h - 1) * 1,
The difference between the two formulas is T(n) = 2h - h - 1, notes :h = log2(n), therefore T(n) = O(n) - O(log2(n)) - 1 = O(logn)
notes : Computational complexity , The premise is that n Large enough , If n Very small , There is no complexity , direct O(1)
3、 ... and 、 Quick line up / Priority queue / Stack row
package everyday.medium;
import java.util.PriorityQueue;
// No k The biggest element .
public class FindKthLargest {
/* target: Take the second in the array K Big element , Put the array in order , take nums[k - 1] that will do , But the time complexity O(nlogn), Not an option . Selection sort , Select the first K individual , Time complexity O(kn), namely O(n), feasible . Stack row , It takes time to build a pile O(nlogn), Choose the first k Big , flowers O(klogn), Time complexity O( ), Is not workable . Why does it take to build a pile O(nlogn)? Our intuitive feeling , To adjust n/2 Time ( Adjust from the penultimate line ), Adjust downward each time O(logn)( Naturally took the biggest one ). So building a pile takes O(nlogn). But this is an illusion . The actual time complexity is Tn = 2^log2(n)^ - log2(n) - 1 =O(n) - O(logn) = O(n)( When n When a large ) prove : Take the full binary tree with the most nodes as an example , Tree height is h, Set the current layer as k, Then this layer has 2^(k - 1)^ Nodes , Each node needs to be adjusted h - k The depth of the . therefore ,T(n) = 2^0^ * (h - 1) + 2^1^ * (h - 2) +...+2^(h - 2) * 1, Obviously, it is a typical difference ratio sequence , Just offset and subtract . 2T(n) = 2^1^ * (h - 1) + 2^2^ * (h - 2) +...+2^(h - 2)^ * 2 + 2^(h - 1) * 1, The difference between the two formulas is T(n) = 2^h^ - h - 1, notes :h = log2(n), therefore T(n) = O(n) - O(log2(n)) - 1 = O(logn) notes : Computational complexity , The premise is that n Large enough , If n Very small , There is no complexity , direct O(1) */
// Selection sort -- Although it is O(n), But time is Tn = kn, Compared with stacking ,Tn = n - log(n+1) + klogn, Still a lot slower .
public int findKthLargest(int[] nums, int k) {
for (int i = 0; i < k; i++) {
// choice
int max = nums[i], idx = i;
for (int j = i + 1; j < nums.length; j++) {
if (max < nums[j]) {
max = nums[j];
idx = j;
}
}
// swap
int t = nums[idx];
nums[idx] = nums[i];
nums[i] = t;
}
// Value
return nums[k - 1];
}
// Stack row , skilled API, Priority queue , The whole big top pile .
public int findKthLargest2(int[] nums, int k) {
// Big pile top
PriorityQueue<Integer> que = new PriorityQueue<>((o1, o2) -> o2 - o1);
// Add elements
for (int num : nums) que.offer(num);
// The first 1 - (k-1) Large elements are taken out
for (int i = 0; i < k - 1; i++) que.poll();
// Take the first place K Big
return que.poll();
}
// Stack row ,API There are too many encumbrances , Direct stacking .
public int findKthLargest3(int[] nums, int k) {
// Building the heap , Start from the node with children on the penultimate layer .
for (int i = nums.length - 1 >>> 1; i >= 0; i--) adjustHeap(nums, i, nums.length);
// Front row K A big element comes out .
int i = 0;
do {
// swap
int t = nums[0];
nums[0] = nums[nums.length - 1 - i];
nums[nums.length - 1 - i] = t;
// Adjust the heap , Make the top of the heap the largest element .
if (++i >= k) break;
adjustHeap(nums, 0, nums.length - i);
} while (true);
// Take the first place k The biggest element
return nums[nums.length - k];
}
// Stack core : Adjust the heap
private void adjustHeap(int[] nums, int k, int end) {
int ori = nums[k]; // Remember the original elements to adjust .
// Keep adjusting downward
for (int i = (k << 1) + 1; i < end; i = (i << 1) + 1) {
// Whether the left child or the right child is older .
if (i + 1 < end && nums[i + 1] > nums[i]) ++i;
// See if it is necessary to exchange with the child .
if (ori >= nums[i]) break;
// Downward adjustments
nums[k] = nums[i];
// Get the new position of the original element .
k = i;
}
// Put the original element in the space it was last swapped to .
nums[k] = ori;
}
}
summary
1) The time complexity of building a heap is O(n), No O(nlogn).
2) Priority queue / Stack row / Selection sort .
reference
边栏推荐
- 最长连续序列
- Does Frankfurt currently support SQL?
- R语言ggplot2可视化:使用patchwork包将两个ggplot2可视化结果纵向堆叠起来(stacking)形成组合图、一个可视化结果堆叠在另外一个可视化结果上
- 深度学习基础汇总
- 从五大能力到 “1+5+N”,华为让政企转型更稳健
- Jackie Chan and fast brand, who is the Savior of Kwai?
- [C language] nextday problem
- ROS knowledge points - definition and use of topic messages
- Spark SQL generate JSON
- With a return of 5000 times, the South African newspaper invested in Tencent to make a province
猜你喜欢

How can the digital intelligent supply chain management platform of the smart Park optimize process management and drive the development of the park to increase speed and quality?

Facebook! Adaptive gradient defeats manual parameter adjustment

【黑马早报】腾讯回应大批用户QQ号被盗;薇娅丈夫公司被罚19万;中国恒大被申请清盘;关晓彤奶茶店回应被加盟商起诉...

C语言学习-20-归并排序

Successful cases of rights protection of open source projects: successful rights protection of SPuG open source operation and maintenance platform

MIPS汇编语言学习-02-逻辑判断-前台输入

SAP mts/ato/mto/eto topic 9: front and back desk operation in m+m mode, strategy 50, preparation of raw materials and semi-finished products in advance

如何从零搭建10万级 QPS 大流量、高并发优惠券系统

Cross cluster deployment of helm applications using karmada

隆重推出 Qodana:您最爱的 CI 的代码质量平台
随机推荐
利用MySqlBulkLoader实现批量插入数据的示例详解
What! One command to get the surveillance?
After QQ was stolen, a large number of users "died"
Oracle11g数据库使用expdp每周进行数据备份并上传到备份服务器
C#/VB. Net to convert PDF to excel
Fleet | "backstage exploration" issue 3: status management
R语言ggplot2可视化:使用patchwork包将两个ggplot2可视化结果纵向堆叠起来(stacking)形成组合图、一个可视化结果堆叠在另外一个可视化结果上
不要使用短路逻辑编写 stl sorter 多条件比较
Li Kou today's question -522 Longest special sequence
GBASE南大通用亮相第六届世界智能大会
隐私计算 FATE - 离线预测
华为能成“口红一哥”,或者“带货女王”吗?
开源大咖说 - Linus 与 Jim 对话中国开源
High "green premium" of environmental protection products? How far is the low-carbon lifestyle from people
Oracle11g database uses expdp to back up data every week and upload it to the backup server
化学制品制造业智慧供应商管理系统深度挖掘供应商管理领域,提升供应链协同
Case driven: a detailed guide from getting started to mastering shell programming
Express模板引擎
R language ggplot2 visualization: use the patchwork package (directly use the plus sign +) to horizontally combine a ggplot2 visualization result and a data table to form a final result graph
Web worker poll request