这段代码的时间复杂度是什么?为什么?

时间:2015-06-15 14:10:51

标签: time-complexity

以下代码的时间复杂度为O(n)。但为什么呢?

int j = 0;
for(int i = 0; i < n; ++i) {
    while(j < n && arr[i] < arr[j]) {
        j++;
    }
}

1 个答案:

答案 0 :(得分:0)

Control passes through the outer loop n times.

Control passes through the inner loop n times at most. That's not n times for each pass through the outer loop, it's n times at most, total.