This is an O (n ^ 2) problem. No other solution is faster than comparing two arrays directly.
Virgil's solution is cool, except that it is not O (n) performance. This is really O (n + 1000). A second array comparison for setting a boolean is expensive and the reverse is failing in small arrays.
The solution you wrote is the best, with the exception of errors.
Here is the bug fixed.
boolean[] matchedPositions = new boolean[n]; for(int k = 0; k < n; k++ { matchedPositions[k] = false; } for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(matchedPositions[j] == false && a[i] == a[j]) { matchedPositions[j] = true; break; } if(j == n - 1) { return false; } } } return true;
In this case, if in the case when the integer matches, then the inner loop will be broken and set or mark the matching position. This is necessary for arrays with duplicate entries , this will avoid two entries in the left array corresponding to one entry in the correct array.
If, in the event that a match does not occur that is identified by j == n - 1 , you will return false.
Since we expect false by default in boolean, it is better to specify the initialize flag.
In fact, this solution has an O (n log n + n) performance penalty. Sorting and comparison have O (n ^ 2 + n) performance limitation. Sorting has an O (n ^ 2) performance and one loop for checking. But sorting modifies the contents of the array, and it is not.
source share