【问题标题】:How to get the N highest numbers on an array while keeping original sorting?如何在保持原始排序的同时获得数组上的 N 个最高数字?
【发布时间】:2017-10-04 12:21:03
【问题描述】:

例如对于 N 个最大的数字,假设 N = 3

我有a,想得到b

 a = np.array([12.3,15.4,1,13.3,16.5])
 b = ([15.4,13.3,16.5])

提前致谢。

【问题讨论】:

    标签: sorting highest


    【解决方案1】:

    好吧,我对此的看法:

    1. 复制原始数组;
    2. 对复制的数组进行排序,找到n个最高的数字;
    3. 遍历原始数组,在将其数字与上一步中的 n 个最高数字进行比较后,将所需的数字移至结果数组中。

    var a = [12.3,15.4,1,13.3,16.5], n = 3, x = 0, c =[]; // c - the resulting array
    var b = a.slice(); // copy the original array to sort it 
    for(var i = 1; i < b.length; i++) { // insertion sorting of the copy
      var temp = b[i];
      for(var j = i - 1; j >= 0 && temp > b[j]; j--) b[j + 1] = b[j];
      b[j + 1] = temp;
    }
    for(var i = 0; i < a.length; i++) { // creating the resulting array
      for(var j = 0; j < n; j++) {
        if(a[i] === b[j]) { 
          c[x] = a[i]; x++; // or just c.push(a[i]);
        }
      }
    }
    console.log(c);

    该示例是用 Javascript 编写的,有点简单,但实际上,它与语言无关,并且可以完成工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 2019-10-10
      • 1970-01-01
      相关资源
      最近更新 更多