简体   繁体   English

如何知道方法是N还是N ^ 2

[英]How to know if method is N or N^2

I often see you guys talking about N methods and N^2 methods, which, correct me if I'm wrong, indicate how fast a method is. 我经常看到你们谈论N方法和N ^ 2方法,如果我错了,请纠正我,指出方法有多快。 My question is: how do you guys know which methods are N and which are N^2? 我的问题是:你们怎么知道哪种方法是N,哪些是N ^ 2? And also: are there other speed indications of methods then just N and N^2? 而且:还有其他方法的速度指示,那么只有N和N ^ 2?

This talks abnout the complexity of an algorithm (which is an indicator of how fast it will be, yes) 这说明了算法的复杂性(这是一个多快的指标,是的)

In short, it tells how many "operations" (with operations being a very vague and abstract term) will be needed for a input to the method of size "N". 简而言之,它告诉对于大小为“N”的方法的输入将需要多少“操作”(操作是非常模糊和抽象的术语)。

eg if your input is an List-type object, and you must iterate over all items in the list, the complexity is "N". 例如,如果您的输入是List类型对象,并且您必须遍历列表中的所有项目,则复杂性为“N”。 (often expressed O(N) ). (通常表示为O(N))。

if your input is an list-type object, and you need only to look at the first (or last), and the list gurantees to you that such a look at the item is O(1); 如果你的输入是一个列表类型的对象,你只需要查看第一个(或最后一个),并且列表保证你看这个项目是O(1); your method will be O(1) - independent from the input size. 你的方法将是O(1) - 独立于输入大小。

If your input is a list, and you need to compare every item to every other item the complexity will be O(N²) or O(N*log(n)) 如果您的输入是一个列表,并且您需要将每个项目与每个其他项目进行比较,则复杂度将为O(N²)或O(N * log(n))

correct me if I'm wrong, indicate how fast a method is. 如果我错了,请纠正我,说明方法有多快。

Its says how an algorithm will scale on an ideal machine. 它说明了算法如何在理想的机器上扩展。 It deliberately ignores the factor involved which can mean that an O(1) could be slower than an O(N) which could be slower than an O(N^2) for your use-case. 它故意忽略了所涉及的因素,这可能意味着O(1)可能比O(N)慢,这可能比你的用例慢O(N ^ 2)。 eg Arrays.sort() will use insertion sort O(N^2) for small collections (length < 47 in Java 7) in preference to quick sort O(N ln N) 例如,Arrays.sort()将使用插入排序O(N ^ 2)用于小集合(Java 7中的长度<47),而不是快速排序O(N ln N)

In general, using lower order algorithms are a safer choice because they are less likely to break in extreme cases which you may not get a chance to test thoroughly. 一般来说,使用低阶算法是一种更安全的选择,因为它们在极端情况下不太可能中断,您可能无法彻底测试。

The way to guesstimate the big-O complexity of a program is based on experience with dry-running code (running it in your mind). 猜测程序的大O复杂性的方法是基于干运行代码的经验(在您的脑海中运行它)。 Some cases are dead obvious, but the most interesting ones aren't: for example, calling library methods known to be O(n) in an O(n) loop results in O(n 2 ) total complexity; 有些情况显而易见,但最有趣的情况不是:例如,在O(n)循环中调用已知为O(n)的库方法会导致O(n 2 )总复杂度; writing to a TreeMap in an O(n) loop results in O(nlogn) total, and so on. 在O(n)循环中写入TreeMap导致总计O(nlogn),依此类推。

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

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