简体   繁体   English

JavaScript 中二次函数的大 O 时间效率

[英]Big O time efficiency for a quadratic function in JavaScript

I am trying to increase the efficiency of a function.我正在尝试提高函数的效率。 It is currently quadratic and I would like to make it logarithmic.它目前是二次的,我想把它变成对数。

The third to last line of the current function is confusing me somewhat as well and I would like some clarification.当前函数的倒数第三行也让我有些困惑,我想澄清一下。

function solution(arr){
   let result = 0
    for ( let i = 0; i < arr.length; i++)
        for (let j = 0; j < arr.length; j++)
            if (arr[i] == arr[j])
                result = Math.max(result, Math.abs(i - j));
         return result;
 }

How do I solve this problem?我该如何解决这个问题?

At least, you could change the indices for looping and omit self checking and to check the same pairs again.至少,您可以更改循环索引并省略自我检查并再次检查相同的对。

function solution(arr){
    let result = 0
    for (let i = 0; i < arr.length - 1; i++)
        for (let j = i; j < arr.length; j++)
            if (arr[i] === arr[j])
                result = Math.max(result, Math.abs(i - j));
    return result;
}

The shortest approach is O(n) by taking an hash table for storing the first found index for a value.最短的方法是 O(n),通过使用哈希表来存储值的第一个找到的索引。

 function solution(array) { var hash = {}; return array.reduce( (m, v, i) => Math.max(m, i - (hash[v] = v in hash ? hash[v] : i)), 0 ); } var array = [1, 3, 4, 5, 1, 3, 4, 5, 6, 2, 3]; console.log(solution(array));

In the above function, the goal is to find the maximum number from array.在上面的函数中,目标是从数组中找到最大数。 Now the meaning of third to last line which is result = Math.max(result, Math.abs(i - j));现在倒数第三行的含义是result = Math.max(result, Math.abs(i - j)); , I will break it into two parts to explain here, ,我这里分成两部分来解释,

First of all, Math.abs(ij) will be executed and provide the absolute value from the difference between i and j .首先,将执行Math.abs(ij)并提供ij之间差异的绝对值。

After this, the outer function Math.max() method will be called which will provide you the maximum value between result and absolute value obtained from first step.在此之后,将调用外部函数Math.max()方法,该方法将为您提供result与第一步获得的absolute value之间的最大值。 Now the maximum value will be store in result .现在最大值将存储在result This is how the function is working.这就是该功能的工作方式。

Now this statement is conditional based, which means it will only execute if arr[i]==arr[j] .现在这个语句是基于条件的,这意味着它只会在arr[i]==arr[j]

I hope it cleared the work flow of this program.我希望它清除了这个程序的工作流程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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