English 中文(简体)
比较计算 成本:i ! = arr[i] - 1 vs. arr[i] != arr[arr[i] - 1] in C++
原标题:Comparing Computational Costs: i != arr[i] - 1 vs. arr[i] != arr[arr[i] - 1] in C++

我有两条幻灯:

for (int i = 0; i < n; i++) {
    while (arr[i] > 0 && arr[i] <= n && i!=arr[i]-1) {
        swap(arr[i], arr[arr[i] - 1]);
    }
}

而且:

for (int i = 0; i < n; i++) {
    while (arr[i] > 0 && arr[i] <= n && arr[i]!=arr[arr[i]-1)] {
        swap(arr[i], arr[arr[i] - 1]);
    }       
}

The difference between the two snippets is in while conditions where in the first we have i!=arr[i]-1 and in 2nd we have arr[i]!=arr[arr[i]-1). The first one runs me into time exceeded issue while the 2nd one runs without any issue.

我正在解决一个编码问题,如果我使用上文提到的首批注射器,我会遇到时间过长的问题,而第2次则不会遇到同样的问题。 其余法典对两种氮都相同。 我混淆了两种条件,即计算上的差别为何。

制约因素:

1 <= n <= 106
-10^6 <= arr[i] <= 10^6
问题回答

Logically, if statement A: arr[i] != arr[arr[i]-1] holds, then statement B: i != arr[i]-1 holds.

换言之,符合A>/em>的一组投入的任何内容(见S_B)必须载于符合B>>/em>的一套投入中。 因此,S_A是S_B的一个子集。 考虑到贵投入空间并不小:1 <=n <= 10^6/code>,且投入可能有很大差异:-10^6 <= arr[i] <= 10^6,S_A > 或许是S_B>/em>的适当子集,而且很可能包含比S_B小得多的内容。

Hence, the number of calls to swap() for S_A is likely to be significantly less than that needed for S_B.





相关问题
How to add/merge several Big O s into one

If I have an algorithm which is comprised of (let s say) three sub-algorithms, all with different O() characteristics, e.g.: algorithm A: O(n) algorithm B: O(log(n)) algorithm C: O(n log(n)) How do ...

Grokking Timsort

There s a (relatively) new sort on the block called Timsort. It s been used as Python s list.sort, and is now going to be the new Array.sort in Java 7. There s some documentation and a tiny Wikipedia ...

Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Enumerating All Minimal Directed Cycles Of A Directed Graph

I have a directed graph and my problem is to enumerate all the minimal (cycles that cannot be constructed as the union of other cycles) directed cycles of this graph. This is different from what the ...

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...