[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))
}

 

posted @   Zhentiw  阅读(212)  评论(0编辑  收藏  举报
编辑推荐:
· 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
点击右上角即可分享
微信分享提示