268 find missing element from An unsortd array
268 find missing element from An unsortd array
If we subtract the sum of the given array from this sum, we get the missing number.
Code:
java
CopyEdit
int n = nums.length;
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
actualSum += num;
• a⊕0=a
If we XOR all numbers in the array with all numbers from 0 to n, the missing number will be left.
Code:
java
CopyEdit
int xor = 0;
int n = nums.length;
xor ^= i;
xor ^= num;
return xor;
We store all numbers in a HashSet and check which number from 0 to n is missing.
Code:
java
CopyEdit
import java.util.HashSet;
set.add(num);
if (!set.contains(i)) {
return i;
Code:
java
CopyEdit
import java.util.Arrays;
Arrays.sort(nums);
if (nums[i] != i) {
return i;
Put each number at its correct index (num[i] = i) and check the missing index.
Code:
java
CopyEdit
int i = 0;
nums[i] = nums[correctIndex];
nums[correctIndex] = temp;
} else {
i++;
if (nums[i] != i) {
return i;
return nums.length;
Code:
java
CopyEdit
int n = nums.length;
expectedSum += i;
actualSum += num;
}
Comparison of Methods