![](/img/trans.png)
[英]Find k number of array elements having the minimum difference amongst themselves
[英]find top k elements in array
我有一個格式的數組:
var series = [[horse,1],[cat,2],[dog,4],[dragon,4],[cow,6]]
為了根據第二個參數找到前3個元素,我對數組進行排序。 所以為此我使用下面的代碼:
series.sort( function(a,b) {
if (a[1] === b[1]) {
return 0;
}
else {
return (a[1] < b[1]) ? 1 : -1;
}
});
哪個工作正常。 那么如果我想找到前三名,我總能選擇[0,2]。 但是,如果第4個值等於3,那么我會想念它。 在這種情況下,如果我要求前3,輸出應該是[[horse,1],[cat,2],[dog,4],[dragon,4]因為龍和狗具有相同的值(4)。 所以,我想知道是否有一些我可以開箱即用的庫或一些有效的算法來返回前3個值,這並不一定意味着返回前3個元素數組?
只需構建一個列表:
var top = [];
top.push(series[0]);
top.push(series[1]);
for (var i = 2; i < series.length && series[i][1] == series[2][1]; ++i)
top.push(series[i]);
概括一點(一點點):
function top(series, k) {
var top = [];
for (var i = ; i < k - 1; ++i)
top.push(series[i]);
for (; i < series.length && series[k-1][1] == series[i][1]; ++i)
top.push(series[i]);
return top;
}
var series = [["horse",1],["cat",2],["dog",4],["dragon",4],["cow",6]]
num = 3;
var arr = [];
for(var i=0; i<series.length; i++)
{
var curr = series[i][1];
var next = series[i][1];
if(i<num)
{
arr.push(series[i]);
}
else if(curr==next)
{
arr.push(series[i]);
break;
}
}
console.log(arr);
所以我會制作第二個數組(長度為3)並循環遍歷初始數組。 當前三個項目應自動添加到數組中。 然后當我們遍歷第一個數組並找到高於最低值的值時,我們刪除最低值並將新項目放在新數組中的適當位置。
var series = [[horse,1],[cat,2],[dog,4],[dragon,4],[cow,6]];
function top3(a){
// Create a new Array to hold the top values
var top = [a[0], a[1], a[2]]; // Initialize it with the first three items
for(var i=3;i<a.length;i++){
/* Find the minimum value and its position */
var min = top[0][1];
var min_pos = 0;
for(var e=1;e<3;e++){
if(top[e][1]<min){
min = top[e][1];
min_post = e;
}
}
/* If larger than the top arrays minimum */
if( a[i][1] > min ){
/* remove the top arrays min */
top.splice(min_pos, 1);
}
/* Add the new item into the top array */
top.push(a[i]);
}
/* Now our "top" array has the items with the top 3 values, if you want them sorted use a bubble sort here, if not just return "top" */
bubbleSortByIndex(a, 1); // Sorts by the second item in an array or arrays
return top;
};
/*
Bubble Sort Algorythm adapted from http://en.wikipedia.org/wiki/Bubble_sort
*/
function bubbleSortByIndex(a, i){
var swapped;
do {
swapped = false;
for(var e=1;e<a.length-1;e++){
if( a[e-1][i] > A[e][i]){
swapped = true;
var temp = a[e-1];
a[e-1] = a[e];
a[e] = temp
}
}
} while (swapped);
return a;
}
top3(series);
這使原始陣列保持原樣,只找到前三個項目,然后對它們進行排序。 如果你想整個原始數組排序,那么只需調用bubbleSortByIndex(series, 1)
並忽略整個“top3()”函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.