[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 ...
随机推荐
- php-cgi segmentation fault nginx
谷歌.百度了一堆后,无果. yum安装软件也报segmentation fault 果断重装系统吧
- socket编程的网络协议
"我们在传输数据时,可以只使用(传输层)TCP/IP协议,但是那样的话,如果没有应用层,便无法识别数据内容" TCP/IP只是一个协议栈,就像程序运行一样,必须要实现运行,同时还要 ...
- Django CRM查询 XXX.object.filter() 常用用法总结
__gt 大于 __gte 大于等于 User.objects.filter(age__gt=10) // 查询年龄大于10岁的用户 User.objects.filter(age__gte=10) ...
- 用python正则表达式提取网页的url
import re import urllib url="http://www.itokit.com" s=urllib.urlopen(url).read() ss=s.repl ...
- websocket初步了解
https://www.cnblogs.com/fuqiang88/p/5956363.html websocket是一种新型的协议,协议标识符为ws,加密即为wss 简单说来就是一种持续的http服 ...
- 洛谷P1280 尼克的任务 [DP补完计划]
题目传送门 题目描述 尼克每天上班之前都连接上英特网,接收他的上司发来的邮件,这些邮件包含了尼克主管的部门当天要完成的全部任务,每个任务由一个开始时刻与一个持续时间构成. 尼克的一个工作日为N分钟,从 ...
- 定位所用的class
方案 为解决类冲突,我们可以使用下述的方案定位一个class所在的位置 ClassName. package cn.j2se.junit.classpath; import static org.ju ...
- 【大视野入门OJ】1083:数组的二分查找
Description 在1500个整数中查整数x的位置,这些数已经从小到大排序了.若存在则输出其位置,若不存在则输出-1. Input 第一行,一个整数x 后面1500行,每行一个整数 Output ...
- PMP的六大管理学定律
★墨菲定律PMP考试六大管理学定律之1-PMP专业辅导 1.什么是墨菲定律?最简单的表达形式是“有可能出错的事情,就会出错(Anything that can go wrong will go wro ...
- [BZOJ2007][NOI2010]海拔(对偶图最短路)
首先确定所有点的海拔非0即1,问题转化成裸的平面图最小割问题,进而转化成对偶图最短路(同BZOJ1002). 这题的边是有向的,所以所有边顺时针旋转90度即可. 如下图(S和T的位置是反的). #in ...