# Java solution, array swap

• Because numbers are from `1` to `n`, after we put number `i` to index `i - 1` there's only 1 `mis-matching` which is the answer. Time complexity O(n). Space complexity O(1).

``````public class Solution {
public int[] findErrorNums(int[] nums) {
int[] result = new int[2];

for (int i = 0; i < nums.length; i++) {
while (nums[i] - 1 != i && nums[nums[i] - 1] != nums[i]) {
swap(nums, i, nums[i] - 1);
}
}

for (int i = 0; i < nums.length; i++) {
if (nums[i] - 1 != i) {
result[0] = nums[i];
result[1] = i + 1;
break;
}
}

return result;
}

private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
``````

• Likewise, I was told that the efficiency of swap() could be improved by using `^` like

``````public void swap(int[] nums, int i, int j){
if (i != j){
nums[i] ^= nums[j];
nums[j] ^= nums[i];
nums[i] ^= nums[j];
}
}
``````

But I got `13ms` runtime, while your solution was `9ms`, any idea why?

• Really smart solution!

• I got the same idea like you!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.