繁体   English   中英

找到数组中的前k个元素

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM