Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3]
return 2
.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
public class Solution {
private void swap(int[] nums, int pos1, int pos2) {
int tmp = nums[pos1];
nums[pos1] = nums[pos2];
nums[pos2] = tmp;
}
public int missingNumber(int[] nums) {
int i = 0;
while(i < nums.length) {
if(i == nums[i] || nums[i] >= nums.length) {
i++;
}
else {
swap(nums, i, nums[i]);
}
}
for(i = 0; i < nums.length; i++) {
if(i != nums[i]) {
return i;
}
}
return nums.length;
}
}