[Algorithm] Find Nth smallest value from Array
Q1: Find the smallest value from array:
function findMin(arr) { let min = arr[0]; for (let i = 1; i < arr.length; i++) { if (arr[i] < min) { min = arr[i]; } } return min; // 1 }
O(n), cannot be improved anymore, because we have to loop though the array once.
Q2: Find 2nd smallest value, naive solution:
function findSndMin(arr) { let min = arr[0]; let min2 = arr[1]; for (let i = 0; i < arr.length; i++) { if (arr[i] < min) { min2 = min; min = arr[i]; } else if (arr[i] !== min && arr[i] < min2) { min2 = arr[i]; } } return min2; // 2 }
Q3: Find nth smallest value:
1. Sorting cannot be the best solution, because it do more works, we only care Nth, means I don't care 0...n-1 is sorted or not or n +1....arr.length is sorted or not.
2. Patition: avg can achieve n + n/2 + n/4 + n/8 .... = 2n ~~ O(n), worse: O(n^2)
function findNthMin(arr, m) { const pivot = arr[0]; let smaller = []; let larger = []; for (let i = 1; i < arr.length; i++) { if (arr[i] < pivot) { smaller.push(arr[i]); } else { larger.push(arr[i]); } } smaller.push(pivot); arr = [...smaller, ...larger]; if (m > smaller.length) { return findNthMin(larger, m - smaller.length); } else if (m < smaller.length) { return findNthMin(smaller, m); } else { return arr[m - 1]; } } const data = [3, 1, 5, 7, 2, 8]; const res = findNthMin(data, 4); console.log(res);
Partition vs Heap:
Why here Heap is not a good solution, because we only need Nth samllest value, we don't care 0..n-1, whether those need to be sorted or not. Heap doing more stuff then necessary.
But if the question change to "Find first K smallest value", then Heap is a good solution.
Mean while we need to be carefull that since we just need K samllest, not all N, then we don't need to add everything into the Heap.
if (h,size() >= K) { if (h.peek() > val(i)) { h.pop() h.add(val(i)) } } else { h.add(val(i)) }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2018-02-06 [Javascript] Delegate JavaScript (ES6) generator iteration control
2017-02-06 [React] Use React.cloneElement to Extend Functionality of Children Components
2017-02-06 [React] Use React ref to Get a Reference to Specific Components
2017-02-06 [React] Normalize Events with Reacts Synthetic Event System
2017-02-06 [NPM] Pipe data from one npm script to another
2017-02-06 [NPM] Pass arguments to npm scripts
2017-02-06 [Vue] Get up and running with vue-router