[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; //
}
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; //
}
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))
}
[Algorithm] Find Nth smallest value from Array的更多相关文章
- algorithm@ find kth smallest element in two sorted arrays (O(log n time)
The trivial way, O(m + n): Merge both arrays and the k-th smallest element could be accessed directl ...
- Yandex.Algorithm 2011 Round 2 D. Powerful array 莫队
题目链接:点击传送 D. Powerful array time limit per test 5 seconds memory limit per test 256 megabytes input ...
- Fast Algorithm To Find Unique Items in JavaScript Array
When I had the requirement to remove duplicate items from a very large array, I found out that the c ...
- Algorithm | Sort
Bubble sort Bubble sort, sometimes incorrectly referred to as sinking sort, is a simple sorting algo ...
- 【pat】algorithm常用函数整理
reference is_permutation Test whether range is permutation of another Parameters first1, last1 Input ...
- [工作积累] 32bit to 64bit: array index underflow
先贴一段C++标准(ISO/IEC 14882:2003): 5.2.1 Subscripting: 1 A postfix expression followed by an expression ...
- 全排列算法(字典序法、SJT Algorithm 、Heap's Algorithm)
一.字典序法 1) 从序列P的右端开始向左扫描,直至找到第一个比其右边数字小的数字,即. 2) 从右边找出所有比大的数中最小的数字,即. 3) 交换与. 4) 将右边的序列翻转,即可得到字典序的下一个 ...
- Algorithm for Maximum Subsequence Sum z
MSS(Array[],N)//Where N is the number of elements in array { sum=; //current sum max-sum=;//Maximum ...
- B. A Leapfrog in the Array
http://codeforces.com/problemset/problem/949/B Dima is a beginner programmer. During his working pro ...
随机推荐
- windows10 易升 下载失败 解决方法
在你剩余最大空间的硬盘里有一个名字大概是Windows10Updata的文件夹里找到一个名字14339开头的升级镜像,把这个文件的名字用记事本保存下来方便以后使用,同时在这个文件夹里还有一个叫prod ...
- 熟悉并了解uml的使用(一)
本资料对UML各种模型图的构成和功能进行说明,通过本资料的学习达到可以读懂UML模型图的目的.本资料不涉及模型图作成的要点等相关知识. UML简介 UML (Unified Modeling Lang ...
- 跨域请求方式之Jsonp形式
在浏览器端才有跨域安全限制一说,而在服务器端是没有跨域安全限制的. 在两个异构系统(开发语言不同)之间达到资源共享就需要发起一个跨域请求. 而浏览器的同源策略却限制了从一个源头的文档资源或脚本资源与来 ...
- C++ 单例模式的几种实现研究
都是从网上学得,整理下自己的理解. 单例模式有两种实现模式: 1)懒汉模式: 就是说当你第一次使用时才创建一个唯一的实例对象,从而实现延迟加载的效果. 2)饿汉模式: 就是说不管你将来用不用,程序启动 ...
- 洛谷P1007 独木桥 [数论]
题目传送门 独木桥 题目背景 战争已经进入到紧要时间.你是运输小队长,正在率领运输部队向前线运送物资.运输任务像做题一样的无聊.你希望找些刺激,于是命令你的士兵们到前方的一座独木桥上欣赏风景,而你留在 ...
- Flask实战第65天:帖子按照发布时间和评论数量等排序
排序,我们需要在前端传递参数, 编辑front_index.html 编辑front.views.py from apps.models import HighlightPostModel from ...
- Redux 中间件的执行顺序理解
Redux.applyMiddleware(thunk, middleware1) 和 Redux.applyMiddleware(middleware1, thunk) 的区别: <!DOCT ...
- JZYZOJ1539[haoi2015]T2 树链剖分
http://172.20.6.3/Problem_Show.asp?id=1539 在学校的OJ又写了一次,RE了好多次,原来haoi的时候这道题需要开栈+快读,裸数据结构30分,加上快读50分.o ...
- 【计算几何】【二分】【随机增量法】hdu6167 Missile Interception
n个半径为R的圆是否有公共部分,等价于询问是否存在一个半径小于R的圆,能覆盖所有n个圆的圆心. 对这n个点求最小圆覆盖即可.从网上扒了个随机增量法的代码. 这样算上二分,复杂度就是nlogn了. #i ...
- Token-Pasting Operator (##) and Stringizing Operator (#)
Token-Pasting Operator (##)The double-number-sign or “token-pasting” operator (##), which is sometim ...