Problem: One can be obtained from one of the arrays.

Whether they are similar.

boolean areSimilar(int[] a, int[] b) { if (Arrays.equals(a,b)){ return true; } int[] c = Arrays.copyOf(a, a.length); boolean fl = true; label:for (int i = 0; i < c.length; i++){ for (int j = i + 1; j < c.length; j++){ int tmp = c[j]; c[j] = c[i]; c[i] = tmp; if (!Arrays.equals(c,b)){ fl = false; c[i] = c[j]; c[j] = tmp; }else{ fl = true; break label; } } } return fl; } 

Is it possible to somehow increase the speed of a particular piece of code? If not, I will be glad to see any other ideas that will be better for this task.

Closed due to the fact that off-topic participants 0xdb , cheops , MedvedevDev , Mr. Black , nick_n_a Jun 19 '18 at 9:11 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • " Learning tasks are allowed as questions only on the condition that you tried to solve them yourself before asking a question . Please edit the question and indicate what caused you difficulties in solving the problem. For example, give the code you wrote, trying to solve the problem "- 0xdb, cheops, MedvedevDev, Mr. Black, nick_n_a
If the question can be reformulated according to the rules set out in the certificate , edit it .

    1 answer 1

    Your solution has a cubic complexity - and this is creepy slowly. And it is solved for linear time.

    Algorithm.

    • Check sizes. They must match.

    • We run through the array and count the elements that are different; we write their indices into the array.

    • If the number of differences is greater than 2 (when passing through the array), then you do not even need to check - you can go, the condition is violated.

    • Having an array of two indices, check whether they are equal in the exchange (you do not even need to change the arrays, just two comparisons).

    • Done!