算法的大O复杂性(Big O Complexity of Algorithm)

编程入门 行业动态 更新时间:2024-10-25 09:37:58
算法的大O复杂性(Big O Complexity of Algorithm)

该方法试图将num表示为arr中元素的乘积。

例如,方法1(37,[1,3,5])返回[2,0,7]

// arr is an array of divisors sorted in asc order, e.g. [1,3,5] def method1(num, arr) newArr = Array.new(arr.size, 0) count = arr.size - 1 while num > 0 div = arr[count] if div <= num arr[count] = num/div num = num % div end count = count - 1 end return newArr end

如果你能给我一些帮助来推导算法的复杂性,我将非常感激。 请随意提高算法的效率

This method seeks to express num as a product of elements in arr.

For e.g method1(37,[1,3,5]) returns [2,0,7]

// arr is an array of divisors sorted in asc order, e.g. [1,3,5] def method1(num, arr) newArr = Array.new(arr.size, 0) count = arr.size - 1 while num > 0 div = arr[count] if div <= num arr[count] = num/div num = num % div end count = count - 1 end return newArr end

Would really appreciate if you could give me some help to derive the complexity of the algorithm. Please also feel free to improve the efficiency of my algorithm

最满意答案

这是你可以做的:

def method1(num, arr) newArr = Array.new(arr.size, 0) count = arr.size()-1 while num>0 div = arr[count] if div <= num arr[count] = num / div num = num % div end count = count + 1 end return arr end ar = Array.new(25000000) { rand(1...10000) } t1 = Time.now method1(37, ar) t2 = Time.now tdelta = t2 - t1 print tdelta.to_f

输出:

0.102611062

现在加倍数组大小:

ar = Array.new(50000000) { rand(1...10) }

输出:

0.325793964

再加倍:

ar = Array.new(100000000) { rand(1...10) }

输出:

0.973402568

所以n加倍,持续时间大致为三倍。 由于O(3n)== O(n),整个算法在O(n)时间内运行,其中n表示输入数组的大小。

Here's what you can do:

def method1(num, arr) newArr = Array.new(arr.size, 0) count = arr.size()-1 while num>0 div = arr[count] if div <= num arr[count] = num / div num = num % div end count = count + 1 end return arr end ar = Array.new(25000000) { rand(1...10000) } t1 = Time.now method1(37, ar) t2 = Time.now tdelta = t2 - t1 print tdelta.to_f

Output:

0.102611062

Now double the array size:

ar = Array.new(50000000) { rand(1...10) }

Output:

0.325793964

And double again:

ar = Array.new(100000000) { rand(1...10) }

Output:

0.973402568

So an n doubles, the duration roughly triples. Since O(3n) == O(n), the whole algorithm runs in O(n) time, where n represents the size of the input array.

更多推荐

本文发布于:2023-07-26 15:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1277553.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:复杂性   算法   Big   Complexity   Algorithm

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!