如何从Javascript数组中获取两个最大的整数并将值返回到DOM?

Rya*_*mes 7 javascript arrays sorting performance

我写了一个解决方案来获取通过表单输入的整数列表.有用.它为您提供了两个最大整数的总和,并将其发布在DOM中.但是,对于100万个整数的大型数组来说,它并不是非常有效.

如何才能提高此解决方案的效率.

App.js

 // This function reverses the order of the array and places the biggest numbers first
 function sortNumber(a, b) {
   return b - a;
 }


 // this function is used to ensure the user didn't enter any letters
 function getArray() {
   var alphaExp = /^[a-zA-Z]+$/;

   // This function takes the array, orders it, adds the sum of the two largest numbers and returns the value

   function sumOf(x) {

       // Sort the ary with the sortNumber function
       array.sort(sortNumber);

     // Then we add the two biggest numbers of the array and save it to the result variable.

       var result = array[0] + array[1];

       // Then we share the result with the user by updating the browser
       var myHeading = document.querySelector('h2');
       myHeading.textContent = "The sum of your two biggest numbers is: " + result;

     // Like a good student, it's important to show your work
       var showYourWork = document.querySelector('h3');
       showYourWork.textContent = array[0] + " + " + array[1] + " = " + result;
     }
     // This grabs the value of the input
   var arrayField = document.getElementById('arrayField').value;

   if (arrayField.match(alphaExp)) {

     // Fail if user enters letters
     var raiseError = document.querySelector('h5');
     raiseError.textContent = 'No not letters! We want numbers!!';
   } else {
     var array = JSON.parse("[" + arrayField + "]");
     if (arrayField.length < 2) {

       // If the user enters only 1 number, tell them to enter more!
       var raiseError = document.querySelector('h5');
       raiseError.textContent = 'Please enter atleast two numbers seperated by commas for us to add!'
     } else {

       // When the user enters a list of numbers, run the sumOf function.
       sumOf(arrayField);

       //Make the error go away
       var raiseError = document.querySelector('h5');
       raiseError.textContent = '';
     }
   }
 };

 // use an eventlistener for the event (This is where the magic happens)
 var subButton = document.getElementById('subButton');
 subButton.addEventListener('click', getArray, false);
Run Code Online (Sandbox Code Playgroud)

dea*_*ndi 3

您不必对其进行排序,只需线性搜索两个最大的:

编辑:下面的代码现在应该可以工作,并且比OP的代码渐近更快。OP 首先进行排序,假设有一个随机列表,这可以在 O(n log n) 内完成。O(cn)我的代码对with中的列表进行线性搜索c = 2(这两个循环不是必需的,但很简单)。ceil(n log n) = 2n正整数的解决方案n是 14,即对于每个长度超过 14 个条目的列表,下面的代码更快。例如:对于一百万个条目,关系是 13,815,511 到 2,000,000,快了六倍多。您可以在单个循环中执行相同的操作,从而将运行时间减半(理论上,但由于更好的局部性,它也会快一点)。

function maxtwo_wrong(a){
    var b1 = -Infinity;
    var b2 = -Infinity;

    for (var i=0; i < a.length; i++) {
        if (a[i] > b1) {
            b1 = a[i];
        }
    }
    for (var i=0; i < a.length; i++) {
        if (a[i] > b2 && a[i] < b1) {
            b2 = a[i];
        }
    } 
    return [b1,b2];
}
Run Code Online (Sandbox Code Playgroud)

EDIT-2:上面的代码maxtwo_wrong似乎不符合要求,所以我又写了一个maxtwo_right放在下面。OP,请告诉我哪一个满足您的要求,以便我删除错误的。

EDIT-3:使其更简单且正确。

function maxtwo_right(a){
    var b1 = -Infinity;
    var b2 = -Infinity;

    for (var i=0; i < a.length; i++) {
        // If the current entry is bigger than variable b1
        // keep the old value in the variable b2 and set b1 to the
        // value of the current entry
        if (a[i] > b1) {
            b2 = b1;
            b1 = a[i];
        }
        // if the current entry equals b1 set the variable b2 to
        // the value of the current entry
        else if(a[i] === b1){
            b2 = a[i];
        }
    }
    // return the sum of the two variables as requested
    return b1 + b2;
}
Run Code Online (Sandbox Code Playgroud)