Javascript:将解决方案更改为O(n log n)

时间:2017-10-05 05:35:30

标签: javascript

以下是我在学习Javascript时遇到的问题的解决方案: - 问题: - 找到他参加锦标赛的击球手对阵球队的最高平均得分。 以下是他在锦标赛中得分的球队得分: -

[    
    ["Srilanka", 23], 
    ["Srilanka", 230],
    ["Pakistan", 127],
    ["India", 3],
    ["India", 71],
    ["Australia", 310],
    ["India", 22],
    ["Pakistan", 1]
]

我写的解决方案代码是: -

function getHighscoreAaverage (input) {
try {
    var matches = JSON.parse(input);
} catch(e) {
    console.error('Error parsing input string...');
    return '';
}

var average_runs = [];
var high_average = 0;
var high_average_country = '';

for ( var i = 0; i< matches.length; i++) {

    if(typeof average_runs[matches[i][0]] === "undefined") {
        average_runs[matches[i][0]] = {
            "total": 0,
            "count": 0,
            "average": 0
        }
    }

    average_runs[ matches[i][0] ]["total"] += matches[i][1];
    average_runs[ matches[i][0] ]["count"] += 1;
    average_runs[ matches[i][0] ]["average"] = average_runs[matches[i][0]]["total"] / average_runs[matches[i][0]]["count"];

}

for (country in average_runs) {
    if(average_runs[country]["average"] > high_average){
        high_average = average_runs[country]["average"];
        high_average_country = country;
    }
}


return high_average_country;
}
getHighscoreAaverage ('[    ["Srilanka", 23], ["Srilanka", 230],    ["Pakistan", 127],    ["India", 3],    ["India", 71],    ["Australia", 310],    ["India", 22],    ["Pakistan", 1]]');

我想与其他程序员核实这段代码是否可以进一步优化。我想提高我的编码水平,对此的任何帮助都将深受赞赏。

建议代码: - 注意:下面的代码没有给出正确答案。

function getHighscoreAaverage (input) {
    try {
        var matches = JSON.parse(input);
    } catch(e) {
        console.error('Error parsing input string...');
        return '';
    }

    var average_runs = [];
    var high_average = 0;
    var high_average_country = '';

    for ( var i = 0; i< matches.length; i++) {

        if(typeof average_runs[matches[i][0]] === "undefined") {
            average_runs[matches[i][0]] = {
                "total": 0,
                "count": 0,
                "average": 0
            }
        }

        average_runs[ matches[i][0] ]["total"] += matches[i][1];
        average_runs[ matches[i][0] ]["count"] += 1;
        average_runs[ matches[i][0] ]["average"] = average_runs[matches[i][0]]["total"] / average_runs[matches[i][0]]["count"];

        if(average_runs[matches[i][0]]["average"] > high_average){
            high_average = average_runs[matches[i][0]]["average"];
            high_average_country = matches[i][0];
        }
    }

    return high_average_country;
}

1 个答案:

答案 0 :(得分:0)

请注意,您的原始解决方案是O(n)(假设实现足够智能),那么为什么要使用O(nlogn)解决方案呢?

无论如何,为了比较最高的平均值,我们必须首先按项目值排序,以使运行的avarages单调......

&#13;
&#13;
var input = [    
    ["Srilanka", 23], 
    ["Srilanka", 230],
    ["Pakistan", 127],
    ["India", 3],
    ["India", 71],
    ["Australia", 310],
    ["India", 22],
    ["Pakistan", 1]
];

var result;

input
  .sort(function(a,b) { return a[1] - b[1]; })
  .reduce(function(a,n){
    if(!a[n[0]]) a[n[0]] = { count: 0, total: 0 };
    
    var entry = a[n[0]];
    
    entry.count ++;
    entry.total += n[1];
    
    var avg = entry.total / entry.count;
    
    if( !result || result.avg < avg )
      result = { name: n[0], avg: avg };
    
    return a;
    },{});

console.log(result);
&#13;
&#13;
&#13;

仅为了您的信息,以下是我如何实施它(在下划线的帮助下),例如:

&#13;
&#13;
var input = [    
  ["Srilanka", 23], 
  ["Srilanka", 230],
  ["Pakistan", 127],
  ["India", 3],
  ["India", 71],
  ["Australia", 310],
  ["India", 22],
  ["Pakistan", 1]
];

var highest_avarage = _.chain(input)
  .groupBy( entry => entry[0] )
  .map( (totals,name) => ({ name: name, avg: totals.reduce( (a,b)=>(a+b[1]), 0 ) / totals.length }) )
  .max( entry => entry.avg );

console.log(highest_avarage);
&#13;
<script src="http://underscorejs.org/underscore-min.js"></script>
&#13;
&#13;
&#13;