简体   繁体   English

如何确定看起来像这样的东西的大O:(x -1)+(x-2)+(x-3)…(x-x)

[英]How to determine big O of something that looks like this: (x -1) + (x - 2) + (x - 3) … (x - x)

I'm trying to brush up on my big o calculations. 我正在尝试重新计算我的大头绪。 If I have function that shifts all of the items to the right of 'i' 2 spaces I have a formula that looks something like: 如果我有将所有项目移到'i'2个空格右侧的函数,则我的公式看起来像:

(n -1) + (n - 2) + (n - 3) ... (n - n)

Where the first iteration I have to move (x-1) items, the second (x-2) items, and so on... the method: 在第一次迭代中,我必须移动(x-1)个项目,在第二个(x-2)项目中移动,依此类推...方法:

int[] s = {1,2,3,4, , }

public static char[] moveStringDownTwoSpaces(char[] s){
    for(int j = 0; j < s.length; j++){

    for(int i = s.length-3; i > j; i--){
        s[i+2] = s[i];
    }
    return s;
    }
}

I know this is O(n^2), but I don't quite understand the math behind transforming this: 我知道这是O(n ^ 2),但我不太了解转换此函数的数学原理:

(n -1) + (n - 2) + (n - 3) ... (n - n)

into this 进入这个

O(n^2)

In my mind if n = 5 (String is of length 5), I would have... 在我看来,如果n = 5(字符串的长度为5),我将...

(5-1) + (5-2) + (5-3) + (5-4) + (5-5) = 5(5 - ???)

which is 这是

(n-1) + (n-2) + (n-3) + (n-4) + (n-5) = n(n - ???)

so that gives me 5*5 = 25 which is n^2. 这样我得到5 * 5 = 25,即n ^ 2。 but what is the ??? 但是什么是??? I don't know what to put for the variables in the formula. 我不知道要在公式中为变量添加什么。 I don't even know if I'm even going by this the correct way. 我什至不知道我是否正以这种正确的方式前进。 AKA I forgot how to do math :( 我又忘了怎么做数学:(

(n -1) + (n - 2) + (n - 3) ... (n - n)

Just rewrite the following as: 只需将以下内容重写为:

1 + 2 + 3 + ....+ (n-1)

which is equal to: (n(n+1)/2 - n) . 等于: (n(n+1)/2 - n)

Now you can see it is O(n^2) . 现在您可以看到它是O(n^2)

As noted by @hvd you may want to put the return statement outside the loop. 正如@hvd所指出的,您可能希望将return语句放在循环之外。

The Big-O notation is not the exact upper bound. Big-O表示法不是确切的上限。 It's an asymptotic upper bound. 这是一个渐近的上限。 In many cases where a algorithm may look like O(n^2), but amortized analysis may show a linear order complexity. 在许多情况下,算法可能看起来像O(n ^ 2),但摊销分析可能会显示线性顺序复杂度。

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

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