[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 ...
随机推荐
- [水煮 ASP.NET Web API2 方法论](1-3)如何接收 HTML 表单请求
问题 我们想创建一个能够处理 HTML表单的 ASP.NET Web API 应用程序(使用 application/x-www-form-urlencoded 方式提交数据). 解决方案 我们可以创 ...
- 前端读者 | 关于存储及CSS的一些技巧
@羯瑞 HTML5存储 cookies 大小限制4K 发送在http请求头中 子域名能读取主域名的cookies 本地存储 localStorage sessionStorage 大小限制5M(注意超 ...
- RecyclerView混合布局
本来想把公司的UI图放上来,考虑到版权等未知因素,就拿网上的图来说了: 类似的这种布局,有的一行只有一张图片,有的一行有两个元素,有个一行有三个元素..就是混合的布局方式 参考文献: https:// ...
- 在浏览器中输入url地址 -> 显示主页的过程
-来自<图解HTTP> 最近在进行前端面试方面的一些准备,看了网上许多相关的文章,发现有一个问题始终绕不开: 在浏览器中输入URL到整个页面显示在用户面前时这个过程中到底发生了什么.仔细思 ...
- ZOJ 3497 Mistwald
矩阵快速幂. 邻接矩阵的$P$次方就是走$P$步之后的方案数,这里只记录能否走到就可以了.然后再判断一下三种情况即可. #pragma comment(linker, "/STACK:102 ...
- js跨域请求实现
js代码 var url = zfba2url + "/fzyw/xzfy/smcl/autoUpdateByWS.action"; var data = { "writ ...
- 贪心【CF1029E】Tree with Small Distances
Description 给定一棵树.要求往树中加入一些边使得从1到其他节点的距离至多是2 . 输出加入边的最小数量.(边全部都是无向的) Input 第一行一个整数n,表示树中的节点个数. 接下来n− ...
- C#代码规范化(代码风格化)的几个函数
近期由于适配Oracle的缘故,将旺财C#.NET代码生成器增加了风格化的几个函数,具体实现如下功能: 1.转换为Pascal风格,如User_Name/USER_NAME/UserName自动替换下 ...
- HashMap的实现原理 HashMap底层实现,hashCode如何对应bucket?
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha 数组和链表组合成的链表散列结构,通过hash算法,尽量将数组中的数据分布均匀,如果has ...
- 【BZOJ 1036】【ZJOI 2008】树的统计Count
http://www.lydsy.com/JudgeOnline/problem.php?id=1036 复习了一下好写好调的lct模板啦啦啦--- #include<cstdio> #i ...