Share the joy
Given a sorted array. Two elements are swapped. Recover this array.
Solution. Think about the case1:
Original array = [1, 2, 3, 4, 5, 6, 7].
Swapped array = [1, 7, 3, 4, 5, 6, 2].
And we have first and second with Integer type. In this way, we know
If arr[i] > arr[i + 1] and first == null, we have first = i.
If arr[i] > arr[i + 1] and first != null, we have second = i + 1
Another exception case happens when the swapped element are together:
Original array = [1, 2, 3, 4, 5, 6, 7].
Swapped array = [1, 3, 2, 4, 5, 6, 7].
In this way,
If arr[i] > arr[i + 1] and first == null, we have first = i, second = i + 1
Considering above 2 cases, below is a concise code for it:
public static void recoverArray(int[] arr) { Integer first = null, second = null; for (int i = 0; i < arr.length - 1; i++) { if (arr[i] > arr[i + 1]) { if (first == null) { first = i; } second = i + 1; } } int tmp = arr[first]; arr[first] = arr[second]; arr[second] = tmp; }
Check my code on github.