I believe that my code is working fine but it failed a few test cases. I don't see the problem.
I'm given a non empty array of integer. I should only need a single swap operation in the array. In other words, I need to check if an array can be sorted into a non-decreasing order by performing only one swap operation.
for example: [1, 3, 5, 3, 7] answer is: true
Asumming that: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [1..1,000,000,000]. Complexity: expected worst-case time complexity is O(N*log(N));
function solution(A) {
var N = A.length;
var cnt = 0;
var B = A.slice();
B.sort();
for (var i = 0; i < N; i++) {
if(A[i] != B[i]) {
cnt++;
}
}
return (cnt < 3);
}
is it not working?
O(N*lgN)complexity.